A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
Environment variables are key-value pairs inherited from the parent process. PATH, HOME, USER, TMPDIR. Your program can read them with getenv, which takes a name and returns a pointer to the value string, or NULL if the variable is not set. The returned pointer points into the environment block. Do not free it. Do not modify it. It is not yours.
#include <stdio.h>#include <stdlib.h>int main(void) {const char *home = getenv("HOME");const char *path = getenv("PATH");const char *missing = getenv("THIS_VAR_DOES_NOT_EXIST");printf("HOME: %s\n", home ? home : "(not set)");printf("PATH: %.60s...\n", path ? path : "(not set)");printf("MISSING: %s\n", missing ? missing : "(not set)");return 0;}
The ternary guard (home ? home : "(not set)") prevents passing NULL to printf's %s, which is undefined behavior. Some libc implementations print "(null)" as a courtesy, but the standard does not require it. Always guard. Environment variables are a common source of configuration: database URLs, API keys, temp directories, feature flags.
The string returned by getenv may be overwritten by a subsequent call to setenv or putenv. If you need the value to persist, copy it with strdup or into your own buffer. Do not store the raw pointer and use it later after modifying the environment.
getenv is how your program discovers its runtime context without hardcoding paths or credentials. Twelve-factor applications live and die by environment variables. Next: system, which runs a shell command from within your C program, and which carries significant security implications.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.