C Language Strings Creating Arrays of Strings

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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.



Got any C Language Question?