Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
August 14th, 2013, 05:56 AM
 zulfi123786
Registered User

Join Date: Jun 2013
Posts: 11
Time spent in forums: 59 m 5 sec
Reputation 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
August 14th, 2013, 06:01 AM
 eramit2010
Contributing User

Join Date: Mar 2013
Location: India
Posts: 95
Time spent in forums: 2 Days 18 h 10 m
Reputation Power: 3
Code:
`p[i]= *(p+i)`

so p+i is address of p[i].

#3
August 14th, 2013, 06:19 AM
 C learner
Contributing User

Join Date: Jul 2013
Posts: 109
Time spent in forums: 2 Days 3 h 47 m 43 sec
Reputation Power: 2
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));```

 Viewing: Dev Shed Forums > Programming Languages > C Programming > Need help in understanding p[1] vs p+1 in array of char pointers