Programming in C

(Barry) #1
Dynamic Memory Allocation 383

the output file by argv[2]. After opening the first file for reading and the second file for
writing, and after checking both opens to make certain they succeeded, the program
copies the file character by character as before.
Note that there are four different ways for the program to terminate: incorrect num-
ber of command-line arguments, can’t open the file to be copied for reading, can’t open
the output file for writing, and successful termination. Remember, if you’re going to use
the exit status, you should alwaysterminate the program with one. If your program ter-
minates by falling through the bottom of main, it returns an undefinedexit status.
If Program 17.1 were called copyfand the program was executed with the following
command line:


copyf foo foo1


then the argvarray would look like Figure 17.1 when mainis entered.


argv[0]


argv[1]


argv[2]


argv[3]


c o p yf

foo\0

f o o1\0

null

\0

Figure 17.1 argvarray on startup of copyf.

Remember that command-line arguments are alwaysstored as character strings.
Execution of the program powerwith the command-line arguments 2 and 16, as in


power 2 16


stores a pointer to the character string "2"inside argv[1], and a pointer to the string
"16"inside argv[2]. If the arguments are to be interpreted as numbers by the program
(as you might suspect is the case in the powerprogram), they must be converted by the
program itself. Several routines are available in the program library for doing such con-
versions, such as sscanf,atof,atoi,strtod,and strtol.These are described in
Appendix B, “The Standard C Library.”


Dynamic Memory Allocation


Whenever you define a variable in C—whether it is a simple data type, an array, or a
structure—you are effectively reserving one or more locations in the computer’s memo-
ry to contain the values that will be stored in that variable.The C compiler automatically
allocates the correct amount of storage for you.

Free download pdf