Reputation: 33
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
Upvotes: 3
Views: 1070
Reputation: 29
Memory Allocation is a bit tricky, but it's easier than you think. It is, as the name implies, the usage and selection of data to optimize program function and speed. Basically, Memory Allocation is a "perk" of languages such as C/C++ that allow programmers to only use EXACTLY as much data as needed, freeing up memory for other computer functions.
Some good info to know about memory...
Variable sizes:
When neighboring elements are of the same type (for example, an array of chars), they will have a difference in address that increments/decrements by the value of the memory size. Since a char variable has a size of 1 byte, neighboring elements will have addresses that differ by 1.
Ex: char addresses: 1204, 1205, 1206, 1207... (1 byte)
int addresses: 1204, 1208, 1212, 1216... (4 bytes)
Upvotes: 0
Reputation: 726479
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]
.
Upvotes: 3