Cannot understand return value of sizeof()

后端 未结 5 510
南旧
南旧 2020-12-11 08:59

I have this in my code:

int x = 4;
char* array = malloc(x*sizeof(char));
size_t arraysize = sizeof (array);
printf(\"arraysize: %zu\\n\", arraysize);
         


        
5条回答
  •  猫巷女王i
    2020-12-11 09:14

    You are calculating the size of the full array (4*sizeof(char)) But you spect to know the number of items on the array (4).

    You can do

    size_t arraysize = sizeof (array)/sizeof(char);

    It will return 8/2 = 4

提交回复
热议问题