Printing all environment variables in C / C++

c c++


How do I get the list of all environment variables in C and/or C++?

I know that getenv can be used to read an environment variable, but how do I list them all?

5/23/2017 8:24:29 AM

Accepted Answer

The environment variables are made available to main() as the envp argument - a null terminated array of strings:

int main(int argc, char **argv, char **envp)
  for (char **env = envp; *env != 0; env++)
    char *thisEnv = *env;
    printf("%s\n", thisEnv);    
  return 0;
11/14/2017 3:05:55 PM


extern char **environ;

int main() {
  int i = 1;
  char *s = *environ;

  for (; s; i++) {
    printf("%s\n", s);
    s = *(environ+i);

  return 0;

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow