Cannot understand return value of sizeof()

2019-01-20 03:17发布

问题:

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);

This code prints out,

arraysize: 8

Why is it 8 and not 4? (Since 4*sizeof(char) = 4 * 1)

回答1:

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.



回答2:

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.



回答3:

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.



回答4:

sizeof(array) returns the size of a pointer.



回答5:

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



标签: c malloc