Reputation: 2464
I have been trying to understand the output of this program:
#include <stdio.h>
int main(){
static int arr[] = {0, 1, 2, 3, 4};
int *p[] = {arr, arr+1, arr+2, arr+3, arr+4};
int **ptr = p;
ptr++;
printf("%d %d %d\n", ptr-p, *ptr-arr, **ptr);
*ptr++;
printf("%d %d %d\n", ptr-p, *ptr-arr, **ptr);
*++ptr;
printf("%d %d %d\n", ptr-p, *ptr-arr, **ptr);
++*ptr;
printf("%d %d %d\n", ptr-p, *ptr-arr, **ptr);
return 0;
}
1 1 1
2 2 2
3 3 3
3 4 4
Could anybody explain the output?
Upvotes: 1
Views: 2471
Reputation: 1
The main thing to consider is the arithmetic operation on the the pointer.
Do the following ie add + 1 = add + 1*(size of the data type of the data which is pointed by that address)
++
and --
also like that.
Upvotes: 0
Reputation: 678
After first ptr++, it would be:
Hence,
printf("%d %d %d\n",ptr-p,*ptr-arr,**ptr);
will give : 1 1 1
After *ptr++ it will be:
Hence,
printf("%d %d %d\n",ptr-p,*ptr-arr,**ptr);
will give : 2 2 2
After *++ptr, it will be:
Hence, printf("%d %d %d\n",ptr-p,*ptr-arr,**ptr);
will give : 3 3 3
After ++*ptr, it will be:
Hence, printf("%d %d %d\n",ptr-p,*ptr-arr,**ptr);
will give : 3 4 4
Hope it helps.
Upvotes: 8
Reputation: 7662
I will try to explain only the first printf
. I think it should be enough to understand the rest of printfs. As someone else noticed, the code is based on playing with pointers arithmetics in C language.
arr
array contains five numbers from 0 to 4.
p
is an array of pointers to integers and it is filled with "addresses" of the numbers stored in arr
.
ptr
is a pointer to a pointer to integer and it is initialized with p
(because in C language an array of pointers is equivalent to a pointer to a pointer).
Then, ptr
is incremented. Keep in mind, we are incrementing the address, so now it points to the (arr+1)
element in p
array.
That's why ptr-p
returns 1. In other words, we're subtracting addresses.
*ptr
points to arr + 1
element. That's why the second value is also equal to 1.
By doing **ptr
we retrieve a value that is stored at arr+1
address and it is also 1.
Upvotes: 0
Reputation: 108986
You might want to read 6.5.6 in the C99 Standard.
Basically, for difference between pointers
Upvotes: 0