cd
~steve/ex/hello.c
hello.c
$ clang -Wall -std=c11 -o hello hello.c $ ./hello
Did it print what you expected?
hello
$ ./hello Adam Bob Cynthia
Modify hello.c such that the “Hello” messages are printed in the reverse order.
Since you have modified hello.c, you need to recompile the program. So once again, run
$ clang -Wall -std=c11 -o hello hello.c $ ./hello Adam Bob Cynthia
If you get an error or warning message, read it closely and then try to fix the error/warning.
If your modified program printed out the line
Hello (null)!
then you have likely tried to print argv[argc] which has the special value NULL. This is an off-by-one error. You should fix this.
argv[argc]
NULL
char *getenv(char const *environment_variable);
function to get the value of environment variables (as a string). In particular, getenv("USER") returns the user name of the user running the program.
getenv("USER")
In order to use getenv, the function needs to be declared before we can use it in main.c. Fortunately, getenv is part of the C standard library and is declared in the stdlib.h header.
getenv
main.c
stdlib.h
Modify hello.c as follows. First, add the line
#include <stdlib.h>
to the top of the file.
Next, modify the first printf() line so that rather than printing Hello world!, it prints Hello followed by the user’s user name. Look closely at the other printf() line for inspiration. Rather than printing out argv[idx], you’ll want to print out getenv("USER").
printf()
Hello world!
Hello
argv[idx]
Compile and run the program. (After editing a file, it’s easiest to press up in the terminal until you get to the clang line and then you can just press enter rather than typing out the whole clang -Wall -std=c11 ... line each time.)
clang
clang -Wall -std=c11 ...