artic sol
artic sol

Reputation: 493

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

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:

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;

}

Upvotes: 2

Views: 238

Answers (1)

dbush
dbush

Reputation: 225007

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.

Upvotes: 2

Related Questions