Thread: Need help in understanding p[1] vs p+1 in array of char pointers

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Jun 2013
Posts
11
Rep Power
0

Need help in understanding p[1] vs p+1 in array of char pointers

Hi

I was playing around with arrays of pointers and got stuck while understanding the difference between p+1 and p[1]

Below is the code and its output:

Code:
```#include <stdio.h>
#include <string.h>

int main()
{
int i=0;
char *p[]={"one","two","three","four","five"};
printf("Value of p is %p\n",p);
printf("Value of p+1 is %p\n",p+1);

for(;i<5;i++){
printf("P+%d is %p\n",i,p+i);
}
for(i=0;i<5;i++){
printf("P+%d is %p\n",i,p[i]);
}
}```
RESULT:
Code:
```Value of p is 0x7fff3a39b000
Value of p+1 is 0x7fff3a39b008
P+0 is 0x7fff3a39b000
P+1 is 0x7fff3a39b008
P+2 is 0x7fff3a39b010
P+3 is 0x7fff3a39b018
P+4 is 0x7fff3a39b020
P+0 is 0x400808
P+1 is 0x40080c
P+2 is 0x400810
P+3 is 0x400816
P+4 is 0x40081b```

Thanks
-Zulfi
2. Code:
`p[i]= *(p+i)`
so p+i is address of p[i].

in your case p+i will print address of pointers variable.
and p[i] will print address of your strings.
3. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Jul 2013
Posts
109
Rep Power
3
p, p+1, p+2, p+3 p+4 are the addresses of your elemens which are the pointers.

What you actually have is an array of pointers and 5 strings, each of them pointed by a pointer from the array of pointers (which are above those strings), and the name "p" is above its elements.

p[0]--->"one"
p[1]--->"two"
p[2]--->"three"
p[3]--->"four"
p[4]--->"five"

Here's one practical use of p, p+1 etc, without the "*" operator. Initiating an array of double pointers, each will point to a pointer from the array "p":
Code:
`char **d_pointer[]={p, p+1, p+2, p+3 p+4} /*since pointers hold addresses that's what these elements shall evaluate to*/`
print the strings like this:
Code:
```printf("%s", p[i]);

OR

printf("%s", *(p+i));

OR

printf("%s", *d_pointers[i]); /* [] takes you down to p[i], and "*" takes you down to the contents pointed by p[i] */

OR

printf("%s", **(d_pointers+i));```