# Thread: Pointer arthematic . Its simple but i am confusing me. wt is diff b/w p+1 and &p+1

1. ## Pointer arthematic . Its simple but i am confusing me. wt is diff b/w p+1 and &p+1

Hi ,

what is the difference between p+1 and &p+1 from below program. I understand that p+1 increase to next value and &p+1 points to value after sizeof(p).

my question the value of p and &p are same. But why final value comes to differ?

Code:
int main()
{
char *p[]={"hai","howareyou"};
printf ("%d\n",p+1);
printf ("%d\n",&p+1);
return 0;
}

2. What is the type of p and what is the type of &p?

3. p is character pointer to an array. &p is address of pointer to any array.

and i getting the output as

1075588900
1075588896

I understand why output is coming like that. But i did not get why it is coming like this. Because value of p and &p are same right?

4. Originally Posted by nkrao123@gmail.
p is character pointer to an array.
No, p is an array of 2 pointers to char. It is converted to a pointer to a pointer to char.

Originally Posted by nkrao123@gmail.
&p is address of pointer to any array.
Since p is an array of 2 pointers to char, the type of &p is a pointer to an array of 2 pointers to char.

Originally Posted by nkrao123@gmail.
I understand why output is coming like that. But i did not get why it is coming like this.

Originally Posted by nkrao123@gmail.
Because value of p and &p are same right?
Yes, but I asked you about the types involved because that determines what the resulting addresses will be. Given an array, if a pointer x points to the first element of the array, (x + 1) points to the second element of the array, if it exists. The address of the first element of the array and the address of the second element of the array differ by the sizeof an element of the array.

In your example, the reason for the difference is that sizeof of a pointer to char is not the same as sizeof an array of 2 pointers to char.

5. Really i am confusing.

if i take the below example
Code:
int main()
{
char a[]={1,2,3};
printf ("%d\n",a+1);
printf ("%d\n",&a+1);
return 0;
}
in above code also a and &a values are same but the valueof a+1 and &a+1 are different .

6. Correct. Pointer arithmetic adds the size of the object pointed to.

a + 1 is of type pointer to char. sizeof(char) is 1, by definition, so a + 1 is equal to &a[1].

&a + 1 is of type pointer to array of three char. sizeof(array of three char) is equal to 3, so &a+1 has value equal to &a[3]. (and, yes, a[3] does not exist).

The same style of logic applies to the example in your first post, except your array of of type array of pointer to char.

Incidentally, use %p to print the value of a pointer, not %d. Converting the value of a pointer to int (which is what happens when you use %d) can change the value.

7. Take a read through Prelude's tutorial on pointers. It is one of the best around and should answer most of your questions.