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

后端 未结 8 1137
醉梦人生
醉梦人生 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.

提交回复
热议问题