int main(int ac, char **av, char **env)
{
unsigned int i = 1;
while(getenv("env[i]") != NULL)
{
printf("%s\n", env[i]);
i++;
}
return 0;
}
Asked
Active
Viewed 77 times
-2

Weather Vane
- 33,872
- 7
- 36
- 56

Dr.Nati M
- 7
- 3
-
3`int i = 0; while(env[i] != NULL) { ... }` – Weather Vane May 11 '22 at 19:34
-
1The argument to `getenv` is the name of an environment variable. If you give it something which is not the name of an environment variable, it returns NULL. – rici May 11 '22 at 19:34
-
Array indexes start at `0`, not `1`. – Barmar May 11 '22 at 19:37
1 Answers
0
As discussed above, arrays start at index 0 and the loop condition is wrong ("env[i]"
is a fixed string, also getenv()
takes a name
but env[i]
is a name=value
pair):
#include <stdio.h>
int main(int ac, char **av, char **env) {
for(unsigned i = 0; env[i]; i++) {
printf("%s\n", env[i]);
}
return 0;
}

Allan Wind
- 23,068
- 5
- 28
- 38
-
yhaa that i did that but i want to insert the var name manually and printout that specific value for the name I inserted how should I proceed – Dr.Nati M May 12 '22 at 05:37
-
That is an entirely different question. If you have the name, say, "PATH", then you call getenv("PATH"). If you don't have the name, then you need to extract it from `env[i]` for example `char *end = index(env[i], '='); if(!end) { ...}; char *name = strndup(env[i], end - env[i] + 1); name[end - env[i]] = '\0'; getenv(name); free(name);` – Allan Wind May 12 '22 at 07:00