The getenv()
function allows you to find the value of a specific environment variable, but doesn't provide a mechanism to scan over the entire list of environment variables. The envp
argument allows you to iterate over the entire list of environment variables, as your demonstration code shows which is simply not feasible using the getenv()
interface.
On POSIX systems, there is a global variable, extern char **environ;
, which also points to the environment. The functions putenv()
(ancient, non-preferred because it presents memory management problems), setenv()
and unsetenv()
can also manipulate the environment variable list (as defined by environ
). A program can directly modify environ
or the values it points at, but that is not advisable.
If you are using fork()
and the exec*()
family of functions, unless you use execve()
and specify the environment explicitly, the child process will receive the environment defined by environ
.
No header declares environ
— AFAIK, it is the only variable defined by POSIX without a header to declare it. The C standard recognizes the int main(int argc, char **argv, char **envp)
signature for main()
as a common extension to the standard, documented in Annex J.