Why sizeof(array) and sizeof(&array[0]) gives different results?

前端 未结 8 1020
悲&欢浪女
悲&欢浪女 2020-12-30 06:56
#include 
int main(void){
    char array[20];

    printf( \"\\nSize of array is %d\\n\", sizeof(array) );  //outputs 20
    printf(\"\\nSize of &         


        
8条回答
  •  情深已故
    2020-12-30 07:39

    The "array" itself is constant pointer, you can not address it to different location. Yes, array address is the same as &array[0], which is derived from &(array+0) and it is equal to &(array). We know that &* is eliminated so we are back to "array" again. So "array" is the same as "&*(array+0)" But in regards to sizeof operator, the operand must be in array notation, not in pointer notation. To clarify:

    char *data = {"Today is Sunday"}; ... Pointer notation

    char data[] = {"Today is Sunday"}; ... Array notation

    In the first example with pointer notation the sizeof(data) will be the size of bytes required to store an address, which is 8 on my system. In the second example the sizeof(data) will give the number of bytes occupied by the array, which would be 15 chars in the string. But if you use pointer notation like sizeof(data+0) the result will be the number of bytes required to store an address, which is 8 on my system.

    sizeof operator result is the same for pointer and for array with pointer notation.

提交回复
热议问题