0

I'm trying to setenv a new environement variable with setenv().

But I noticided that setenv() function set my new environement variable only if I use the environement "extern char **environ"

But I want to use the argument of the main() : "char **envp".

Here's the code I tried to do for setting in envp, but as you will see if you run that code, it won't be set in envp.

But if I use const char **environ it works.

Any ideas ?

#include <stdlib.h>
#include <stdio.h>

int     main(int ac, char **av, char **envp)
{
  int   i;

  i = 0;
  setenv("NEW_ENV_VAR", "hello_world", 0);
  while (envp[i])
    printf("%s\n", envp[i++]);
  return (0);
}
Difender
  • 495
  • 2
  • 5
  • 18

1 Answers1

1

setenv() is documented to not be allowed to change the optional envp argument to main.

If you need to iterate through all the environment variables, use the extern char **environ variable.

See also this question.

Community
  • 1
  • 1
nos
  • 223,662
  • 58
  • 417
  • 506
  • So, I have to recode setenv(), if I want to use envp, right ? – Difender May 12 '14 at 12:27
  • No. `envp` is a *local variable* in `main` and there is fundamentally no way for an external function to modify it. Use `extern char **environ;`. Or if you insist on using the `envp` variable, just write `envp = environ;` in `main` somewhere after the `setenv` call. – R.. GitHub STOP HELPING ICE May 12 '14 at 12:38