Cannot understand return value of sizeof()

后端 未结 5 509
南旧
南旧 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条回答
  • 2020-12-11 09:05

    sizeof(array) returns the size of a pointer.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-11 09:21

    array is a pointer in your code. sizeof(array) therefore returns the size of that pointer in C bytes (reminder: C's bytes can have more than 8 bits in them).

    So, 8 is your pointer size.

    Also, the correct type specifier for size_t in printf()'s format strings is %zu.

    0 讨论(0)
  • 2020-12-11 09:21

    array is a pointer, hence it will be size of a pointer(sizeof(void *) or sizeof(char *)), and not sizeof(char) as you might expect. It seems that you are using 64bit computer.

    0 讨论(0)
  • 2020-12-11 09:24

    sizeof doesn't have a return value because it isn't a function, it's a C language construct -- consider the fact that you can write sizeof array without the parentheses. As a C language construct, its value is based entirely on compile-time information. It has no idea how big your array is, only how big the array pointer variable is. See http://en.wikipedia.org/wiki/Sizeof for complete coverage of the subject.

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