Question

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);
}
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top