2

This is the code https://ide.geeksforgeeks.org/8bYOzDDC9U to run this

#include <stdio.h>

char *c[] = {"GeksQuiz", "MCQ", "TEST", "QUIZ"};
char **cp[] = {c+3, c+2, c+1, c};
char ***cpp = cp;

int main()
{
    cpp++;
    printf("%s", cpp[0][0]);  // TEST
    printf("%s ", cpp[-1][-1]); // TEST
    return 0;
}

The output of both the printf() is TEST. Why is it so? When I do cpp++, the pointer moves to c+2. SO I understand that cpp[0][0] will be at the starting of "TEST" and that's why it is printing TEST. Can someone explain me for cpp[-1[-1]?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
ABD
  • 180
  • 11

2 Answers2

2

char ***cpp = cp; initializes cpp to point to the first element of cp, that is, cp[0].

After cpp++, cpp points to cp[1]. Then cpp[-1] refers to cp[0].

cp[0] contains c+3, which is a pointer to c[3]. So cp[0][-1] refers to c[2].

c[2] contains "Test", in the sense that it is a pointer to the first element of "Test", so printing it prints "Test".

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
1

Initially the pointer cpp points to the first element of the array cp.

char ***cpp = cp;

After this statement

cpp++;

the pointer cpp points to the second element of the array cp. So this expression

cpp[-1]

gives the first element of the array cp

Pay attention to that the expression cpp[-1] is calculated like

*( cpp - 1 )

Thus in fact these two statements

cpp++;

and

cpp[-1]

may be considered like *( ( cpp += 1 ) - 1 ) that has the same effect if to write cpp[0] without incrementing the pointer cpp.

This (first ) element of the array cp. contains the value c+3 that is the pointer to the last element of the array c.

So cpp[-1][-1]give the element before the last element of the array c that is the pointer to the first character of the string literal "TEST".

Thus the string literal is outputted by this call of printf

printf("%s ", cpp[-1][-1])

Also bear in mind that in the presented code there is neither 2-d array. All arrays, c and cp, are one-dimensional arrays of pointers.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • How can we consider cpp++ and cpp[-1] as cpp[0] ? This is something I don't understand in terms of pointers. – ABD Apr 17 '20 at 05:05
  • @AkhileshGangwar Consider x + 1 - 1. What is the result? It is in fact the same as cpp++ - 1 because the result of cpp++ is cpp + 1. – Vlad from Moscow Apr 17 '20 at 07:49
  • I was assuming something else. :P Thanks. I got it. :) – ABD Apr 17 '20 at 09:49