Skip to main content
Logo image

Section 21.6 Arrays of Strings

How do we store a list of names in an array? A name is stored in an array of characters, so we kind of need an array of arrays? We’ll talk about such multi-dimensional arrays soon, but for now we’ll use a slightly different method: an array of pointers.

Activity 21.5.

Write a C program that reads a list of first names from the file "names.txt" (a test file can be accessed in the coding window below if you are using our code tool - if you work on the servers directly, please simply create your own input file "names.txt"). For each name that you read you need to reserve space in memory using malloc() to store the name. To do so, you can either read the name first into a temporary variable, find its length, and then allocate the relevant memory (don’t forget about the null terminator), or you may assume that no name has more than 50 characters and allocate that same amount of space for each name read. In addition to allocating space for the name read and placing the name read into that space, you also need to store the pointer to the name in an array of pointers. You may assume that there are no more than 20 names in the file.
When you are done reading all of the names, call a function printNames(), to which you pass the array of pointers along with the number of names you read, and which prints out the list of names. Finally, call a function freeNames(), to which you again pass the array of pointers as well as the number of names stored in it, and which frees the space allocated for each name.

admin.....open in new window

When you are done, please paste your code into the code submission box below: