Why are asterisks needed for array variable?

Viewed 72

Looking at the code segment down below, array in C language is already a pointer saving the address of the first element of the array, so why the asterisk is needed for argv variable?

char *argv[3]; 

argv[0] = "echo";
argv[1] = "hello";
argv[2] = 0;
exec("/bin/echo", argv);
printf("exec error\n");
5 Answers

argv is an array of pointers to char. So argv[0] is a char*, as is argv[1], and so on.

You read the type from highest-precedence operator outwards from the name being declared. Since [] (array operator) has higher precedence than * (indirection), you read it as:

  • argv
  • ...is an array ([])
  • ...of pointers (*)
  • ...to char.

This array declaration

char *argv[3]; 

declares an array with 3 elements of the type char *. That is elements of the array are pointers and these pointers (except the last) are assigned with addresses of first characters of string literals

argv[0] = "echo";
argv[1] = "hello";
argv[2] = 0;

To make it more clear you could declare the array for example the following way

char * ( argv[3] ); 

or

char * ( argv )[3]; 

Or for example using a typedef

typedef char * T;
T argv[3];

And the assignments can look like

argv[0] = &"echo"[0];
argv[1] = &"hello"[0];
argv[2] = NULL;

array in C language is already a pointer

No, it "decays" to a pointer to the first item when used in most expressions. That doesn't make an array a pointer.

But in this case that's completely irrelevant, since the purpose is to create an array of pointers (to string literals).

Arrays in C aren't actually pointers, but in many cases decay to a pointer to the first element in the array.

In this case, argv is an array of char *. So each array element can hold a pointer to the start of a string.

char *argv[3] is an array of 3 char pointers.

To put it another way, char *arg would be a single char pointer. A single char pointer could be "hello".

int nums[3] would be an array of 3 numbers. nums[0] could be 1, nums[2] be 2, and nums[2] be 3.

Therefore, char *argv[3] is an array that holds 3 char pointers. It can hold 3 char pointers like in your example.

You could technically use char argv[][] instead, and have an array holding an array of chars. The reason we don't do this is that the lengths of the char arrays are variable, and since array need a strictly-defined size, we'd like run into errors this way. Using pointers allows us to have variable sizes, which is what we want.

Related