In: Computer Science
Please explain answer so I can understand.
1. Write a C program that prints out its command line arguments,
one to a line.
Discussion: A C program starts at a function called main. main has two arguments, conventionally named argc and argv. argc is of type int; it’s the argument count, an integer that contains the number of command line arguments (including the program name). argv is the argument vector; it’s an array of pointers to characters, In C this is described as char *argv[] (or, equivalently and confusingly, char **argv - because C doesn’t really have arrays.)
Imagine that the command line is
% myprog pizza burrito kale
Then what’s actually happening is that somewhere in memory, when the program begins execution, the shell (working with the C runtime library) has arranged that the strings “myprog”, “pizza”, “burrito”, “kale” are stored somewhere in memory, AND that a table of four addresses - the addresses of the first characters of those strings - is also stored somewhere in memory. These addresses are pointers. In principle these strings can be anywhere but in practice they occupy consecutive memory locations. The diagram on the next page shows a picture in which I have arbitrarily chosen location 1128 as the address of the ‘m’ in “myprog” and 2020 as the address of the (nameless) table where the pointers to the strings are stored. In this example, the value of argc is 4 and the value of argv is 2020. The value of *argv is 1128. (What is its type?)The value of **argv is ‘m’. (What is its type? What is the value of argv[1]?)
2. Modify your program to print the arguments in reverse order.
The C program along with the comments is given below.
#include <stdio.h>
//arguments to the main function: argc and argv
int main(int argc, char** argv)
{
//display the contents of argv using for
loop
printf("Arguments in the same order as
given:-\n");
for (int i = 0; i < argc; i++)
printf("%s\n",
argv[i]);
//display the contents of argv in the reverse
order using for loop [Modification]
printf("\nArguments in the reverse order as
given:-\n");
for(int i=argc-1; i>=0; i--)
printf("%s\n",
argv[i]);
return 0;
}
If the indendations are not clear, then please refer the screenshots of the code given below.
Command line arguments given were as follows:-
Output obtained is also given below.
Explanation:-
Hope this helps. Doubts, if any, can be asked in the comments.