0

This is regarding single-char pointers and double-char pointers. Here I am trying to initialize a double-pointer with an array of strings while defining the new pointer.

I have tried

char arry[] = "Hello World"
char* cptr = "Hello World"

It works fine and the difference is the second line is only read-only. In the same way, I am trying to use double pointers

char *darry[] = {"Hello", "World", "C", "Ubuntu"}; 
char **da = {"Hello", "World", "C", "Ubuntu"};

I thought the double pointer(da) would work the same as the single pointer but it is giving me an error. Could anyone point me in the right direction? Thanks

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
crack_49
  • 1
  • 1
  • 5
    ```char *array[]``` declares an array of pointers to ```char```. ```char **da``` is a pointer to pointer to ```char```. There's a difference. – Harith Dec 28 '22 at 16:41
  • Tip: Use a `NULL` terminator in lists like this, as in `char* x[] = { "a", "b", ..., NULL }` This way if you pass it in to a function where your array decays into a pointer you can still find the end. – tadman Dec 28 '22 at 16:46

1 Answers1

0

char *darry[] is an array.

{"Hello", "World", "C", "Ubuntu"} is a valid initializer for an array of char *.

char **da is a pointer.

char **da = {"Hello", "World", "C", "Ubuntu"}; fails as {"Hello", "World", "C", "Ubuntu"} is not a valid initializer for a pointer.

To initialize a non-char * pointer to the first element of an array, form the array of char * with a compound literal. The array is then converted to the address of its first element as part of the initialization - which is a char **.

//          v-----------------------------------------v Array of char *.
char **da = (char *[]){"Hello", "World", "C", "Ubuntu"};
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256