3

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)

Chris
  • 3,619
  • 8
  • 44
  • 64
  • 1
    @modifiablelvalue: Yes I've meant zu.I've changed it. Well,it's the first time I am pointed to that site, thank you for the info! You can calm down by the way, I am a student learning to program, and yes it was the first time I got this problem! So once again, do calm down! – Chris Mar 26 '13 at 09:27
  • It returns ptr size. Even if you make x value as 1000 it will return only 8. – Jeyamaran Jul 30 '14 at 06:39

5 Answers5

7

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.

Alexey Frunze
  • 61,140
  • 12
  • 83
  • 180
3

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.

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
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.

Jim Balter
  • 16,163
  • 3
  • 43
  • 66
2

sizeof(array) returns the size of a pointer.

Eric Urban
  • 3,671
  • 1
  • 18
  • 23
-2

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