Quixotic
Quixotic

Reputation: 2464

Output Explanation: A complicated pointer arithmetic

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;
}

OUTPUT

1 1 1
2 2 2
3 3 3
3 4 4

Could anybody explain the output?

Upvotes: 1

Views: 2471

Answers (4)

jailani
jailani

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

Furquan
Furquan

Reputation: 678

This is the initial snapshot

After first ptr++, it would be: enter image description here Hence, printf("%d %d %d\n",ptr-p,*ptr-arr,**ptr); will give : 1 1 1

After *ptr++ it will be:enter image description here Hence, printf("%d %d %d\n",ptr-p,*ptr-arr,**ptr); will give : 2 2 2

After *++ptr, it will be:

enter image description here

Hence, printf("%d %d %d\n",ptr-p,*ptr-arr,**ptr); will give : 3 3 3

After ++*ptr, it will be:

enter image description here

Hence, printf("%d %d %d\n",ptr-p,*ptr-arr,**ptr); will give : 3 4 4

Hope it helps.

Upvotes: 8

Lukasz
Lukasz

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

pmg
pmg

Reputation: 108986

You might want to read 6.5.6 in the C99 Standard.

Basically, for difference between pointers

  1. they must point within the same array (or one past the end)
  2. the difference is the number of elements that separate the pointers (or number of bytes divided be size, in bytes, of each element).

Upvotes: 0

Related Questions