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

后端 未结 8 1060
醉梦人生
醉梦人生 2020-12-22 10:47

Consider the following code

#include 

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

int main(){
 char string[] =         


        
相关标签:
8条回答
  • 2020-12-22 10:59

    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.

    0 讨论(0)
  • 2020-12-22 11:00

    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

    0 讨论(0)
  • 2020-12-22 11:01

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

    0 讨论(0)
  • 2020-12-22 11:04

    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

    0 讨论(0)
  • 2020-12-22 11:12

    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 讨论(0)
  • 2020-12-22 11:17

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

    0 讨论(0)
提交回复
热议问题