Reputation: 315
I am not getting how the following thing is working?
void main()
{
static int a[] = {10, 12, 23, 43, 43};
int *p[] = {a, a + 1, a + 2, a + 3, a + 4};
int **ptr = p;
ptr++;
printf("%d,%d,%d", ptr - p, *ptr - a, **ptr);
}
This is giving the output as 1 1 10
. I get that **ptr
gives the value stored at ptr
but why is ptr-p
giving 1
should it not give sizeof(int)
?
Upvotes: 0
Views: 222
Reputation: 1306
To explain output I commented the of code snippet:
#include <stdio.h>
int main()
{
// a is an array of integers
static int a[]={10, 12, 23, 43, 43};
// p is an array of integer pointers. Each of the element, holds address of elements in array "a"
// p[0] = &a[0], p[1] = &a[1], p[2] = &a[2], p[3]=&a[3], p[4]=&a[4]
int *p[]={a, a + 1, a + 2, a + 3, a + 4};
// ptr is a pointer to an integer pointer. Ptr holds base address of array "p"
// ptr = &p[0]
// *ptr = *(&p[0]) = p[0]
// **ptr = *(p[0]) = *(&a[0]) = a[0] = 10
int **ptr = p;
// ptr was pointing to zeroth element in the p array, which is p[0].
// Incrementing pointers, makes it to move by X bytes and hence point to the next element.
// where X = sizeof(int *). int* is p's datatype.
ptr++;
// ptr = &p[1]
// *ptr = *(&p[1]) = p[1]
// **ptr = *(p[1]) = *(&a[1]) = a[1] = 12
// pointer difference is measured by the number of elements
// since ptr points to p+1. difference is 1
printf("ptr - p: %p\n", (void*)(ptr - p) );
// ptr holds address of p+1. *ptr holds value of p[1], which as explained in the above holds address of a[1].
// Hence difference of (a+1) - a is 1
printf("*ptr - a: %p\n", (void* )(*ptr - a));
// ptr holds address of p+1. *ptr holds address of a[1]. **ptr holds value of a[1].
printf("**ptr: %d\n", **ptr);
return 0;
}
Have printf statements and validate the comments I have provided in the program for better understanding.
For Example. Compare p[0]
and &a[0]
. Compare *p[3]
and a[3]
.
Hope the code and the comments help you.
Provided code is compilable and output on my screen is
ptr - p: 0x1
*ptr - a: 0x1
**ptr: 12
Upvotes: 3
Reputation: 122383
In pointer arithmetic, ptr - p
will output the number of elements from p
to ptr
, not the size from p
to ptr
. The size of elements is not relevant.
BTW, your code doesn't compile. A minimal example to illustrate your question looks like this:
#include <stdio.h>
int main()
{
static int a[] = {10,12,23,43,43};
int *p = a;
int *ptr = p;
ptr++;
printf("%p %p %d\n", (void*)ptr, (void *)p, ptr - p);
return 0;
}
Output on my machine:
0x600b44 0x600b40 1
Upvotes: 2
Reputation: 308121
Pointer arithmetic is done using the size of the element pointed to. Since you used ++
on ptr
, the difference is going to be 1
no matter what type ptr
is.
Upvotes: 1