1 #include <stdio.h>
2 #include <stdlib.h>
3
4 extern char **environ;
5 void output(char *a[], char *b[]) {
6 int c = atoi(a[0]);
7 for (int i = 0; i < c && b[i]; ++i) {
8 printf("%s", b[i]+2);
9 }
10 }
11
12 void main(int argc, char *argv[]) {
13
14 switch (argc) {
15 case 1:
16 for (int i = 0; environ[i]; ++i) {
17 printf("%s\n", environ[i]);
18 }
19 break;
20 default:
21 output(argv + 1, environ + 2);
22 exit(argc);
23 }
24 }
After executing the command $ ./m0 (assuming that the code above was compiled with $ gcc m0.c -o m0), suppose that the output is
A=9
B=4
C=1
D=4
E=5
What is the output of executing this command $ ./m0 2 3 4
5?
(atoi(str) converts the string argument str to an integer)
The program prints 14 and exits with exit code 5.
Explanation:
argv contains items passed on the command line, i.e. the array of
strings m0,2,3,4,5.
argv + 1 points to the array 2,3,4,5 which is what gets passed to
output as the first parameter.
Looking at the first run, the external array environ contains the
strings "A=9","B=4","C=1", "D=4","E=5", null
environ + 2 therefore points to "C=1", "D=4","E=5", null
In output, the parameters are (a = {"2", "3", "4", "5"}, b =
{"C=1", "D=4","E=5", null})
Therefore c in line 7 will contain 2 and the loop will run two
times
The first time, it will look at "C=1" and print starting from
offset 2, i.e "1"
The second time, it will look at "D=4" and print starting from
offset 2, i.e. "4"
Since there is no space or any other characters printed, the output
shows up as 14
Get Answers For Free
Most questions answered within 1 hours.