Navigation(slideshow)

Chapter 5 - Pointers and Arrays

A pointer is a variable that contains the address of a variable. Pointers are much used in C, partly because they are sometimes the only way to express a computation, and partly because they usually lead to more compact and efficient code than can be obtained in other ways. Pointers and arrays are closely related; this chapter also explores this relationship and shows how to exploit it.

Pointers have been lumped with the goto statement as a marvelous way to create impossible-to-understand programs. This is certainly true when they are used carelessly, and it is easy to create pointers that point somewhere unexpected. With discipline, however, pointers can also be used to achieve clarity and simplicity. This is the aspect that we will try to illustrate.

The main change in ANSI C is to make explicit the rules about how pointers can be manipulated, in effect mandating what good programmers already practice and good compilers already enforce. In addition, the type void * (pointer to void) replaces char * as the proper type for a generic pointer.

  1. ["/5.1 Pointers and Addresses"]
  2. ["/5.2 Pointers and Function Arguments"]
  3. ["/5.3 Pointers and Arrays"]
  4. ["/5.4 Address Arithmetic"]
  5. ["/5.5 Character Pointers and Functions"]
  6. ["/5.6 Pointer Arrays; Pointers to Pointers"]
  7. ["/5.7 Multi-dimensional Arrays"]
  8. ["/5.8 Initialization of Pointer Arrays"]
  9. ["/5.9 Pointers vs. Multi-dimensional Arrays"]

Navigation(children)

1. 5.10 Command-line Arguments

In environments that support C, there is a way to pass command-line arguments or parameters to a program when it begins executing. When main is called, it is called with two arguments. The first (conventionally called argc, for argument count) is the number of command-line arguments the program was invoked with; the second (argv, for argument vector) is a pointer to an array of character strings that contain the arguments, one per string. We customarily use multiple levels of pointers to manipulate these character strings.

The simplest illustration is the program echo, which echoes its command-line arguments on a single line, separated by blanks. That is, the command

   1    echo hello, world

prints the output

   1    hello, world

By convention, argv[0] is the name by which the program was invoked, so argc is at least 1. If argc is 1, there are no command-line arguments after the program name. In the example above, argc is 3, and argv[0], argv[1], and argv[2] are "echo", "hello,", and "world" respectively. The first optional argument is argv[1] and the last is argv[argc-1]; additionally, the standard requires that argv[argc] be a null pointer.

attachment:pic511.gif

The first version of echo treats argv as an array of character pointers:

ch3n2k.com | Copyright (c) 2004-2020 czk.