Skip to content
CurriculumChapter 21 ยท Pointers & Memory
IntermediateHigh focus~14 min

Array of Pointers & Command-Line Arguments

An array of pointers stores several addresses. It is how C represents an array of strings and how main receives command-line arguments.

In plain English

An array of pointers is a list of addresses, like a row of signs pointing to different houses.

01

Arrays of pointers and arrays of strings

An array of pointers stores addresses, not the objects themselves. char *names[3] holds three pointers to char, which can point to three different strings. The strings themselves may live in read-only storage, so do not modify string literals. An array of pointers is not the same as a 2-D char array: the pointers can point to strings of different lengths.

chapter-21.cC
char *names[3] = {"Ada", "Grace", "Linus"};
for (int i = 0; i < 3; i++) {
    printf("%s\n", names[i]);
}
02

Command-line arguments

main can receive command-line arguments as int argc and char *argv[]. argc is the number of arguments, including the program name. argv[0] is the program name, argv[1] is the first user argument, and argv[argc] is a null pointer. Always check argc before reading an argument.

chapter-21.cC
int main(int argc, char *argv[]) {
    if (argc > 1) {
        printf("first arg: %s\n", argv[1]);
    }
    return 0;
}

Key takeaways

  • An array of pointers stores addresses.
  • char *names[] represents an array of strings.
  • argc counts arguments including the program name.
  • argv[argc] is a null pointer.

Common pitfalls

  • Modifying a string literal through a char * pointer.
  • Reading argv[1] without checking argc.
  • Confusing an array of pointers with a 2-D char array.

Key focus

  • Know the relationship between argc and argv.
  • Trace arrays of pointers and their targets.

Quick check

0 / 2 answered

1. What is argv[0]?

2. What does char *names[3] declare?