开发者

Sizeof doesn't return the true size of variable in C

Consider the following code

#include <stdio.h>

void print(char string[]){
 printf("%s:%d\n",string,sizeof(string));
}

int main(){
 char string[] = "Hello World";
 print(str开发者_如何学Going);
}

and the output is

Hello World:4

So what's wrong with that ?


It does return the true size of the "variable" (really, the parameter to the function). The problem is that this is not of the type you think it is.

char string[], as a parameter to a function, is equivalent to char* string. You get a result of 4 because that is the size, on your system, of a char*.

Please read more here: http://c-faq.com/aryptr/index.html


It is the size of the char pointer, not the length of the string.

Use strlen from string.h to get the string length.


string is a pointer and its size is 4. You need strlen probably.


a array will change into a pointer as parameter of function in ANSI C.


Except when it is an operand of the sizeof or unary & operators, or is a string literal being used to initialize another array in a declaration, an array expression will have its type implicitly converted ("decay") from "N-element array of T" to "pointer to T" and its value will be the address of the first element in the array (n1256, 6.3.2.1/3).

The object string in main is a 12-element array of char. In the call to print in main, the type of the expression string is converted from char [12] to char *. Therefore, the print function receives a pointer value, not an array. In the context of a function parameter declaration, T a[] and T a[N] are both synonymous with T *; note that this is only true for function parameter declarations (this is one of C's bigger misfeatures IMO).

Thus, the print function is working with a pointer type, not an array type, so sizeof string returns the size of a char *, not the size of the array.


A string in c is just an array of characters. It isn't necessarily NUL terminated (although in your case it is). There is no way for the function to know how long the string is that's passed to it - it's just given the address of the string as a pointer.

"String" is that pointer and on your machine (a 32 bit machine) it takes 4 bytes to store a pointer. So sizeof(string) is 4


You asked the systems for the sizeof(the address to the begining of a character array), string is an object, to get information about it's lenght out you have to ask it through the correct OO interface.

In the case of std::string the member function string.length(), will return the number of characters stored by the string object.


http://www.java2s.com/Code/Cpp/Data-Type/StringSizeOf.htm see here it has same output as yours...and find what ur doing wrong

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜