c multiple indirection - assigning a char** to an array of char*

248 Views Asked by At

A char** is a pointer to a char*. This means that the value of a char** is the address of a char*. The value of a char* is the address of the first element in a character array stored in memory.

So in the code below:

  • char* words[3]; is an array of 3 pointers to character arrays, aka char*.
  • char** ppc; is a pointer to a char*

My question is how can you assign ppc = words when words is an array of char*s.

char* words[LENGTH];

int main(int argc, char **argv) {

  char** ppc;

  words[0] = "one";
  words[1] = "two";
  words[2] = "three";

  for (int i =0; i < LENGTH; i++) {
    printf("%s\n", words[i]);
  }

  ppc = words; 

  return 0;

}
1

There are 1 best solutions below

0
On

In most contexts, an array can decay to a pointer to the first element of the array.

In this example, words is an array of pointers to char, i.e. it has type char *[]. An element of this array has type char *, so ppc = words assigns &words[0], which has type char **, to ppc.