Sarkis Sarkis - 2 months ago 14
C Question

sizeof Char / Array length Memory allocation in C,

Can somebody tell me about the memory allocation in c?
What is the size of a char variable? 2 or 4?
Why the difference in the address value between 2 neighboring char elements in an array is only 1?

char foo [] = {'a', 'b'};
printf ("This is the Address of val1 %d \n", &foo[1]); // -1079295441
printf ("This is the Address of val2 %d \n", &foo[2]); // -1079295440
printf ("The size of each array member is %d \n", sizeof(foo)); // 2

Answer

You are not printing addresses correctly: an address is not an int, so you cannot use %d to print it. Use %p (for "pointer") instead, and cast the address to void* for printing:

printf ("This is the Address of val1 %p\n", (void*)&foo[1]);

Now your program produces this or similar output:

This is the Address of val1 0xffbd2fcf 
This is the Address of val2 0xffbd2fd0 
The size of each array member is 2

Two pointers are off by 1, which is the size of a single char. The size of the entire array is 2. If you want to print the size of a single element, use foo[0].

Comments