#include<stdlib.h>
int main()
{
char ch, *p1, **p2, ***p3, ****p4;
ch='a';
p1=&ch;
printf("%c %d %c\n", ch, p1, *p1);
p2=&p1;
printf("%d %d %c\n", p2, *p2, **p2);
p3=&p2;
printf("%d %d %d %c\n", p3, *p3, **p3, ***p3);
p4=&p3;
printf("%d %d %d %d %c\n", p4, *p4, **p4, ***p4, ****p4);
}
The output looks like :
a 298923415 a
298923416 298923415 a
298923424 298923416 298923415 a
298923432 298923424 298923416 298923415 a
Why is it that for p1 and p2 the address assigned is in increment of 1 and for p3 and p4 the address assigned is in increment of 8?
Do the addressing follow any pattern as they are assigned in continuous memory location?
Your objects are laid out sequentially in memory in this case. They don't necessarily have to be though. The compiler can lay things out in memory however it wants.
In your case, your memory looks something like this:
298923415 +-----------+
| 'a' | ch
298923416 +-----------+
| |
| |
| |
| 298923415 | p1
| |
| |
| |
| |
298923124 +-----------+
| |
| |
| |
| 298923416 | p2
| |
| |
| |
| |
298923132 +-----------+
| |
| |
| |
| 298923424 | p3
| |
| |
| |
| |
298923140 +-----------+
| |
| |
| |
| 298923432 | p4
| |
| |
| |
| |
+-----------+
Remember that, on most modern systems, pointer-to-object types are just integers whose job is to store a memory address. On your system (I'm guessing x86_64) pointers have a size of 8 bytes. This is totally system-dependent though. For example, a pointer is 4 bytes on 32-bit x86 systems, and there are plenty of other platforms with exotic pointer sizes.
Also the size of a char
is defined to be 1, so the first pointer sits one byte after ch
.