views:

148

answers:

4

Hi I am new to pointers in C. I know the basic concepts. In the below code, why is it printing the "ink" as its 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);
}

Thanks

+12  A: 

Let's 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"

This implies that:

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

Which means:

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

so **p + 1 is a pointer to this string: {'i', 'n', 'k', '\0'}, which is simply "ink".

Nathan Fellman
A: 

I'd advise that you work backwards from what you know was printed (the 'ink' in 'pink') and see where the different variables must be pointing for that to happen.

Remember that an array can be viewed as a pointer to its first element and that a string can similarly be viewed as a pointer to its first character.

Andrew Aylett
A: 

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

     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

that time it point to "pink".

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

If you print **(p+1), that time it will print "white". Because in the initialization of double pointer you initialize the "s+2". So that time it will points to the "white".

muruga
Note that `p` is an array of double pointers. In C an array is equivalent to a pointer, so `p` is actually a triple pointer as well.
Nathan Fellman
+3  A: 

s is an array of char * (which represent strings).

ptr is an array of pointers to pointers (pointing to the values of s, which are pointers to strings)

p is set to point to ptr[0] (which is a pointer to s[3] or "violet")

p is incremented to point to ptr[1], which points to s[2] or "pink"

In the printf statement p is dereferenced twice. The first deref is a pointer to s[2], the second deref gets you the value of s[2] - "pink". The +1 shifts the pointer to the start of "pink" on by one char, so printing from here to the end of the string will give you "ink".

Rodion Ingles