How to Work with Empty char Arrays in C Programming - dummies

How to Work with Empty char Arrays in C Programming

By Dan Gookin

Just as you can declare an empty, or uninitialized, float or int array, you can create an empty char array with C programing. You must be precise, however: The array’s size must be 1 greater than the maximum length of the string to account for that NULL character. Also, you have to ensure that whatever input fills the array doesn’t exceed the array’s size.

In Filling a Char Array, the char array firstname at Line 5 can hold 15 characters, plus 1 for the at the end of the string. That 15-character limitation is an assumption made by the programmer; most first names are fewer than 15 characters long.


#include <stdio.h>
int main()
 char firstname[16];
 printf("What is your name? ");
 printf("Pleased to meet you, %sn",firstname);

An fgets() function in Line 8 reads in data for the firstname string. The maximum input size is set to 16 characters, which already accounts for the null character because fgets() is smart that way. The text is read from stdin, or standard input.

Exercise 1: Create a new project using the source code from Filling a Char Array. Build and run, using your first name as input.

Try running the program again, but fill up the buffer: Type more than 15 characters. You’ll see that only the first 15 characters are stored in the array. Even the Enter key press isn’t stored, which it would be otherwise when input is fewer than 15 characters.

Exercise 2: Modify your source code from Exercise 4 so that the program also asks for your last name, storing that data in another array. The program should then greet you by using both your first and last names.

Yes, the Enter key press is stored as part of your name, which is how input is read by the fgets() function. If your first name is Dan, the array looks like this:

firstname[0] == 'D'
firstname[1] == 'a'
firstname[2] == 'n'
firstname[3] == 'n'
firstname[4] == ''

That’s because input in C is stream oriented, and Enter is part of the input stream as far as the fgets() function is concerned. You can fix this issue by obeying Exercise 6.

Exercise 3: Rewrite your source code from Exercise 5 so that the scanf() function is used to read in the first and last name strings.

Of course, the problem with the scanf() function is that it doesn’t check to ensure that input is limited to 15 characters — that is, unless you direct it to do so:

Exercise 4: Modify the scanf() functions in your source code from Exercise 6 so that the conversion character used is written as %15s. Build and run.

The %15s conversion character tells the first scanf() function to read only the first 15 characters of input and place it into the char array (string). Any extra text is then read by the second scanf() function, and any extra text after that is discarded.