开发者

pointers increment in c

#include<stdio.h>
int main()
{
   static char *s[]={"black","white","pink","violet"};
   char **ptr[]={s+3,s+2,s+1,s},***p;
   char a[]={"DEAD"};
   p=ptr;
   ++p;
   printf("%c\n",a[0]);
   printf("%s\n",*s); //black 
   printf("%s\n",*s+1); //lack
   //printf("%s\n",s+1);
   printf("%s\n",s[0]);//black   
   printf("%s\n",s[1]);//wh开发者_StackOverflowite
   printf("%s\n",s[2]);//pink
   printf("%s\n",s[1]);//violet
   printf("%s\n",s[1]+1);//hite
   printf("%s\n",s[1]+6);//pink
   printf("%s\n",**p+1); // how does this prints ink
   return 0;
}

output:

D black lack black white pink white hite pink ink

please help to understand


so, p is a pointer to a pointer to a string, which basically is a pointer to a char.

p itself points to the first element of the ptr array; after p++ it points to the second, which is s+2.

s+2 points to the third element in the s array, which is "pink"

these are the two levels od dereferencing performed by **p

now, **p points to the first character of "pink", thus **p+1 points to the 'i'

now, printf takes the pointer to the i and prints everything until the next null byte, resulting in "ink" being printed to your console.


I assume you have no problem with lines I haven't directly copied

printf("%s\n",*s+1); //lack

*s+1 is the same as (*s) + 1

printf("%s\n",s[1]+6);//pink

s[1]+6 is the same as (s[1]) + 6. s[1] has type char*, so s[1]+6 points 6 characters to the right. But it's illegal to do that: s[1] only points to 6 valid characters. You just had (bad) luck that your program didn't crash.

printf("%s\n",**p+1); // how does this prints ink

approximately the same things go for **p+1 :)


You have to understand pointers.

s[0] is exactly the same as *s.

If you have s[0]+1, it points one char further than s[0].

s[1] is the same as *(s+1), but it is completely different from *s+1, which is the same as s[0]+1.

You have to draw arrows on a blackboard.


p = ptr;
++p; /* p now points to the second element of ptr "s+2" */
/* s+2 points to the third element of s "pink" */
/* **p+1 will point to the second character of "pink", thus "ink"; essentially **(s+2)+1 */
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜