the size of string
-
when i trace the following code,the value of "size" is alwarys 4 instead of 14, why? int size; char *str; str = (char*)malloc(128); sprintf(str,"string1\ string2") size = sizeof(str); gucy
First of all, you know you're using C, not C++, right ? 4 is the size of a 32 bit number, i.e. the number which stores the memory address where your string lives. You're looking for strlen, I believe. Or use C++ instead, for example std::string or CString if you're using MFC ( or ATL in VC7, I believe ). Of course, if you're learning, it is indeed better that you understand what the string classes do for you, but sizeof is the wrong approach, it's strlen you want. Christian NO MATTER HOW MUCH BIG IS THE WORD SIZE ,THE DATA MUCT BE TRANSPORTED INTO THE CPU. - Vinod Sharma Anonymous wrote: OK. I read a c++ book. Or...a bit of it anyway. I'm sick of that evil looking console window. I think you are a good candidate for Visual Basic. - Nemanja Trifunovic
-
when i trace the following code,the value of "size" is alwarys 4 instead of 14, why? int size; char *str; str = (char*)malloc(128); sprintf(str,"string1\ string2") size = sizeof(str); gucy
The sizeof keyword gives the amount of storage, in bytes, associated with a variable or a type. Which means that in your case your are getting the size of str which is nothing but a pointer. A pointer stores a memory location, which is only 4 bytes. If you truly want to get the size in bytes of your string that you should try this:
size = sizeof(char) * strlen(str)
// Afterall, I realized that even my comment lines have bugs