Can anyone explain how his printing output is like "ink",

I am new to pointers to C. I know the basic concepts. In the code below, why does it print “ink” as output?

#include<stdio.h>


main()
{
    static char *s[]={"black","white","pink","violet"};

    char **ptr[]={s+3,s+2,s+1,s},***p;

    p=ptr;

    ++p;

    printf("%s",**p+1);
}

thank

+3
source share
4 answers

Let trace it:

ptr = {pointer to "violet", pointer to "pink", pointer to "white", pointer to "black"}

p = ptr --> *p = pointer to "violet"

++p -->     *p = pointer to "pink"

It means that:

*p = {'p','i','n','k','\0'}

It means:

**p = 'p'
**p + 1 = 'i'

therefore, **p + 1is a pointer to this line: {'i', 'n', 'k', '\0'}which is simple "ink".

+14
source

sis an array of char *(representing strings).

ptris an array of pointers to pointers (pointing to values sthat are pointers to strings)

p ptr[0] ( s[3] "" )

p ptr[1], s[2] ""

printf p . deref s[2], deref s[2] - "pink". +1 "" char, "".

+3

, ( "" "" ), , , .

, .

0

static char * C [] = {"black", "white", "pink", "purple"};

     In the above statement you are initialize. 

     char **ptr[]={s+3,s+2,s+1,s}

       In the above statement you are assign pointer s value to ptr

value. And declare a triple pointer.

    p=ptr; 
    In the above statement you assign the double pointer address to

triple pointer.

   ++p; 

   In the above statement you increment the triple pointer value. So

at that time he points to "pink."

   But you are print the **p+1. That time it will print only "ink".

If you type ** (p + 1), then this time will print "white." Because in the initialization of a double pointer, initialize "s + 2". So this time will indicate "white."

0
source

Source: https://habr.com/ru/post/1737312/


All Articles