Naruto Uzumaki
Naruto Uzumaki

Reputation: 998

Array of strings and char ** environ variable

I want to know how an array of strings is declared? What I do is I declare an array of pointers of pointers to strings. Eg.

char *array[]= {"string1","string2","string3"};

I was reading about modifying environment variables in Linux and stumbled upon the pointer char **environ ( http://www.cs.bham.ac.uk/resources/courses/2005/17423/doc/libc/Environment-Access.html#Environment-Access ).

char **environ is declared as an array of strings. I think it should be a pointer to a pointer. For eg.

char *array[]= {"string1","string2","string3"};
 environ = array;

Am I doing something wrong?

I also read somewhere that char *argv[] = char **argv. How is it possible?

Edit: I also found this thread to be very helpful. Should I use char** argv or char* argv[] in C?

Upvotes: 0

Views: 1917

Answers (3)

SivGo
SivGo

Reputation: 224

In C a string is basically just an array of chars. in addition an array name also represents its address.

this is the reason why argv[] is the address of the array of chars (which is a string) and *argv is also the address of the string (since it's the address of the first char).

Upvotes: 1

Jens Gustedt
Jens Gustedt

Reputation: 78943

you are mixing up two different things that are in fact difficult to know for someone who is learning C. Declaration of variables inside a function and as a function parameter are not the same thing. The equivalence

char*argv[] ~~~ char **argv

holds because this a parameter (of main). There the array is in fact the same thing as declaring a pointer.

Your assignment environ = array is not wrong, syntactically, the compiler will accept it. But it is wrong semantically for several reasons:

  • You don't know who and how is allocated *environ.
  • You loose the reference to the initial contents of *eviron.
  • You assign a local storage that will be recycled once you leave the scope of the function. So *environ will be undefined, once you left the function.

So environ is a particularly bad example to do such an assignment.

Upvotes: 1

Bram
Bram

Reputation: 765

well the problem is this. In your program are several pointer. One you asign to a array of strings and one called environ that points to the environment variables. What you say to C with environ = array is give environ the same value as array.. but array has a pointer to a local array. So after that statement the environ pointer will just point to the array you made but has not made any changes to its previous content.

I think you need to strcpy all elements of array to environ. Or use a api call setenv (i think it is)

and to you'r second question. Yes the first pair of [] can always be rewritten to a pointer. so array[] = *array as is array[][5] = (*array)[5] and there for *array[] = **array

i hope to have helped you.

Upvotes: 1

Related Questions