Michael
Michael

Reputation: 13616

Is variable array of pointers or pointer to array?

I study C language and I have some difficulty to understand pointers and arrays.

In tutorial that I read I have this row:

 char* arrP1[] = { "father","mother",NULL }; 

And my question is what is arrP1?

Is it array of pointers to the static strings:

enter image description here

Or it is pointer to the string array:

enter image description here

I am confused...what is arrP1?

Upvotes: 3

Views: 75

Answers (3)

TV1989
TV1989

Reputation: 39

Not sure if this will help or make things more confusing but arrP1 can be both an array of char* and a char**, like so:

void foo1(char** arr) { cout << arr << endl; }
void foo2(char* arr[]) { cout << arr << endl; }

int main() {
  char *arr[] = {"a", "b"};
  cout << arr << endl;

  foo1(arr);
  foo2(arr);
  return 0;
}

The interesting thing (that I just found out myself) is that foo2 doesn't create a copy of the array on its stack, it's passed arr directly! All 3 cout print the same address.

Related SO Q&A

Upvotes: 1

samuelnj
samuelnj

Reputation: 1637

arrP is an array of char * which in this case is an array of size 3, and you've assigned the pointers to c-style strings with initial values of {"father", "mother", NULL}, which themselves are character arrays that are null terminated. So, your first answer is correct.

Upvotes: 3

To find answer for such declerations, you can use cdecl. It'll highly likely answer you.

declare arrP1 as array of pointer to char

However, there is a something that is called as spiral rule. It can also help you to read decleration. For example,

char *str[10]

         +-------+
         | +-+   |
         | ^ |   |
    char *str[10];
     ^   ^   |   |
     |   +---+   |
     +-----------+

-   str is an array of 10 elements
-   str is an array of 10, of pointers
-   str is an array of 10, of pointers, of type char

Upvotes: 2

Related Questions