Allocating memory for strings
Neither of the methods above is any good if a program is going to be fetching a lot of strings from a user. It just isn't practical to define lots of static strings and expect the user to type into the right size boxes! The next step in string handling is therefore to allocate memory for strings personally: in other words to be able to say how much storage is needed for a string while a program is running. C has special memory allocation functions which can do this, not only for strings but for any kind of object. Suppose then that a program is going to get ten strings from the user. Here is one way in which it could be done:
- Define one large, static string (or array) for getting one string at a time. Call this a string buffer, or waiting place.
- Define an array of ten pointers to characters, so that the strings can be recalled easily.
- Find out how long the string in the string buffer is.
- Allocate memory for the string.
- Copy the string from the buffer to the new storage and place a pointer to it in the array of pointers for reference.
- Release the memory when it is finished with.