The gets Function

The third function used to get data from the user, is the gets function. This function gets an entire string of characters from the user and stores them in a set of consecutive memory locations.

This set of memory locations is called an array. This array is defined on the third line of our program proper, and is given the name buffer. Once again, an array can have any name that we choose, so long as it is not a reserved word. Twenty memory locations are set aside for buffer, each capable of holding a single char.

Now you may notice something strange here. The function gets is going to store the string of characters it gets from the user in the array buffer, and so it needs to modify the contents of this array. However, we do not put an ampersand in front of buffer.

This is due to another peculiarity of C. The name of an array is actually already a pointer to a memory location. In fact, it points to the location of the first entry of the array. Therefore, since the name buffer is already an address, we do not need to add an ampersand in front of it.

This has actually been done on purpose by the creators of C. The reason is that arrays can be very large. As we said above, the alternative to passing the address of a variable to a function, is to pass a complete copy of the contents of that variable. In the case of an array, that would mean making a copy in memory of the entire array. If the array was very large this would obviously be very inefficient, so C discourages this possibility by making an array name, a pointer by default.

Of course to print the contents of the array buffer, we use the format identifier %s to tell printf that we want to print a string of characters. It also alerts printf to expect the name of an array as one of its parameters instead of a variable.