Anyone please elaborate what is happining here?
int main()
{
int **p = 0;
//p=? and why| *p=? and why|**p=? and why
++p;
//p=? and why| *p=? and why|**p=? and why
printf("%d\n", p);
return 1;
}
output:-
- 4 (why?)
Anyone please elaborate what is happining here?
int main()
{
int **p = 0;
//p=? and why| *p=? and why|**p=? and why
++p;
//p=? and why| *p=? and why|**p=? and why
printf("%d\n", p);
return 1;
}
output:-
First of all, p
is a pointer to a pointer-to-integer.
int **p = 0;
p
= 0, *p
= nothing, **p
= less than nothing.
++p;
Same as p = p + 1. Means the size of one pointer to a pointer-to-int further. A pointer is basically, at least on your OS, 32 bits length (4 bytes). p
now points 4 bytes after 0. The value of p
is 4.
p
is a pointer to a pointer-to-int
. It's being initialised to 0
, i.e. it's a null pointer.
It's then being incremented to point at the next consecutive pointer-to-int
in memory.* The next pointer will be at address 4, because on your platform the size of a pointer is 4 bytes.
Then printf interprets the pointer value as an integer, and so displays "4".
* Note, however, that this is now undefined behaviour.
It is clear. You have a pointer to a pointer to int (int **p
means a pointer to a pointer to int), that actually holds the address 0). A pointer in itself, in your architecture, is 32 bits (4 bytes) long, so incrementing p
gives you p+4, that is, 0+4 = 4.
Go get a nice C book and learn about pointer arithmetic. You'll be glad the rest of your life! :)
++p
is actually undefined behaviour, but what appears to have happened on your implementation is that sizeof(int*)
is 4, and a null pointer is address 0. Recall that pointer increment, when it's not UB, adds a number of bytes to the address equal to the size of the referand type. So it's not all that surprising that when you take a null pointer of type int**
(hence the referand type is int*
) and increment it, you end up at the address 4
. It's just not guaranteed.
Passing a pointer when the %d
format expects an int
is also undefined behavior, but it appears that the representation of int
and int**
are sufficiently compatible, and the varargs calling convention on your implementation treats them sufficiently similarly, that it has successfully printed 4
. That's also not very surprising for implementations where sizeof(int) == sizeof(int**)
, but also isn't guaranteed.
Of course since it's undefined behavior, there are other possible explanations for what you see.
p is a pointer to pointer to int. And it's initialized to 0, i.e. NULL.
When you increment it, it now points to next pointer to int, which, on 32-bit systems, happens to be 4.