Creating Arrays of Strings

suggest change

An array of strings can mean a couple of things:

  1. An array whose elements are char *s
  2. An array whose elements are arrays of chars

We can create an array of character pointers like so:

char * string_array[] = {
    "foo",
    "bar",
    "baz"
};

Remember: when we assign string literals to char *, the strings themselves are allocated in read-only memory. However, the array string_array is allocated in read/write memory. This means that we can modify the pointers in the array, but we cannot modify the strings they point to.

In C, the parameter to main argv (the array of command-line arguments passed when the program was run) is an array of char *: char * argv[].

We can also create arrays of character arrays. Since strings are arrays of characters, an array of strings is simply an array whose elements are arrays of characters:

char modifiable_string_array_literals[][4] = {
    "foo",
    "bar",
    "baz"
};

This is equivalent to:

char modifiable_string_array[][4] = {
    {'f', 'o', 'o', '\0'},
    {'b', 'a', 'r', '\0'},
    {'b', 'a', 'z', '\0'}
};

Note that we specify 4 as the size of the second dimension of the array; each of the strings in our array is actually 4 bytes since we must include the null-terminating character.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents