argv and argcargc for a program invoked with:
% a.out 100 0
argc = 3
% a.out
argc = 1
% ls -la
argc = 2
% cp file1 file2a
argc = 3
% cp file1 file2a
argc = 3
argc?
argc is an integer.
Its declaration within the parameter list to main
will appear as
int argc
argc?
argc is 1.
There must be at least one, which will be the name of the
invoked program.
argv array
associated with the following command line?
% vim prog.source.c
argv array?
* char ).
argv for the command line:
% simulate 100 -12
argv
--- --- -----------------------------------
| -|----> | -|----> | s | i | m | u | l | a | t | e |\0 |
--- |---| -----------------------------------
| -|----> | 1 | 0 | 0 |\0 |
|---| ---------------
| -|----> | - | 1 | 2 |\0 |
|---| ---------------
% a.out -filename xyz -verbose
A. Which string does argv[2] refer to?
*(argv[1] + 2) ?
% prog3 300 5 -Quiet
Write a C code fragment that changes the
upper case 'Q'
to a lower case 'q'.
/*
* This fragment could be combined into a single assignment
* statement.
*/
char *charptr; /* declaration */
charptr = argv[3]; /* the 'Q' is in the 4th string */
*(charptr + 1) = 'q'; /* 'Q' is the second character within the string */
% process <n> <filename>
where <n> is replaced by an integer value,
and <filename> is the name of a file.
If the following code represents the C source code
that is compiled to be the executable called process,
what is wrong with the code?
#include <stdlib.h>
main(int argc, char *argv[]){
int n;
n = atoi(argv[1]);
}
This program calls the function atoi()
with function with a potentially nonexistent parameter.
There is no guarantee that the user invoked the process
program giving it the assumed arguments.
Show how to fix this code (fragment).
#include <stdlib.h>
main(int argc, char *argv[]){
int n;
/* check for existence of command line argument */
if (argc == 3) {
n = atoi(argv[1]);
}
}
| Copyright © Karen Miller, 2007 |