Home > front end >  Why are asterisks needed for array variable?
Why are asterisks needed for array variable?

Time:06-16

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");

CodePudding user response:

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.

CodePudding user response:

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).

CodePudding user response:

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.

CodePudding user response:

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;
  • Related