2

Basically, I have an array of char* that I want to pass and modify in this function, so I pass in a pointer to an array of char*. That is, I want to pass a pointer to char* arr[]. What is the difference between the two?

user1337532
  • 23
  • 1
  • 3

2 Answers2

8

As always, http://cdecl.org is your friend:

  • char * (*arr)[] - "declare arr as pointer to array of pointer to char"
  • char *** arr - "declare arr as pointer to pointer to pointer to char"

These are not the same. For a start, the first is an incomplete type (in order to use a pointer to an array, the compiler needs to know the array size).

Your aim isn't entirely clear. I'm guessing that really all you want to do is modify the underlying data in your array of char *. If so, then you can just pass a pointer to the first element:

void my_func(char **pointers) { 
    pointers[3] = NULL;  // Modify an element in the array
}

char *array_of_pointers[10];

// The following two lines are equivalent
my_func(&array_of_pointers[0]);
my_func(array_of_pointers);

If you really want to pass a pointer to an array, then something like this would work:

void my_func(char *(*ptr)[10]) {
    (*ptr)[3] = NULL;  // Modify an element in the array
}

char *array_of_pointers[10];

// Note how this is different to either of the calls in the first example
my_func(&array_of_pointers);

For more info on the important difference between arrays and pointers, see the dedicated chapter of the C FAQ: http://c-faq.com/aryptr/index.html.

Oliver Charlesworth
  • 252,669
  • 29
  • 530
  • 650
0

If you have a function that has char *(*arr)[] as a parameter, you will need to pass in an array with the address operator:

void afunc(char *(*arr)[]);

char *charptra, *charptrb, *charptrc;
char *arr[] = {charptra, charptrb, charptrc};

afunc(&arr);

On the other one, you have to pass a pointer that points to a pointer that points to a pointer:

void afunc(char ***);

char arr[] = "str";
char *arrptr = arr;
char **arrptrptr = &arrptr;
char ***arrptrptrptr = &arrptrptr;

afunc(arrptrptrptr);
Espresso
  • 4,684
  • 1
  • 22
  • 33