Search code examples
cpointersputchar

Pointer to two dimensional array


Considering the following code:

int main()
{
    static char wer[3][4] = {"bag","let","bud"};
    char (*ptr)[4] = wer;

    putchar(*(*(ptr+1)+2));
    putchar(*(wer[1]+2));
    putchar(*(ptr+1)+2);

    return 0;
}

the first and second putchar() statement points to the 1st row's 1st element i.e e (considering 0 as the base location), whereas in the 3rd putchar() statement, it shows a garbage value.
But as far as the statement says, (*(ptr+1)) clearly means point to the 2nd row. Why does it happens so?
Is it due to some putchar() norm, or am I complete off the pointer concept?


Solution

  • You are passing the wrong type to putchar in the last line.

    Type of (ptr+1) is char (*)[4].
    Type of *(ptr+1) is char [4], which decays to char*.
    Type of *(ptr+1)+2 is char*.

    The pointer gets converted to some strange int, which explains the output -- or garbage as you put it more clearly.

    When in doubt, it is better to simplify your code than to wonder what's happening.

    Using

    char c = *(ptr+1)+2;
    putchar(c);
    

    might have revealed the problem sooner.