How to Store Strings in C Programming

By Dan Gookin

When a C program needs text input, it’s necessary to create a place to store that text. Right away, you’ll probably say, “Golly! That would be a string variable.” If you answered that way, you’re relying upon your knowledge that text in C programming is referred to as a string.

Alas, you’re wrong.

C lacks a string variable type. It does, however, have character variables. Queue up enough of them and you have a string. Or, to put it in programming lingo, you have an array of character variables.

The array is a big topic. Be open-minded about arrays and strings and soak in the goodness of Stuffing a String into a char Array.

STUFFING A STRING INTO A CHAR ARRAY

#include <stdio.h>
int main()
{
  char prompt[] = "Press Enter to explode:";
  printf("%s",prompt);
  getchar();
  return(0);
}

Line 5 creates an array of char variables. The array is a gizmo that lists a bunch of variables all in a row. The char array variable is named prompt, which is immediately followed by empty square brackets. It’s the Big Clue that the variable is an array. The array is assigned, via the equal sign, the text enclosed in double quotes.

The printf() statement in Line 7 displays the string stored in the prompt array. The %s conversion character represents the string.

In Line 8, getchar() pauses the program, anticipating the Enter key press. The program doesn’t follow through by exploding anything, a task left up to you to code at a future date.

Exercise 1: Create a new project, ex0710, and type the source code from Stuffing a String into a char Array. Build and run the code.

Exercise 2: Modify the source code from Stuffing a String into a char Array so that a single string variable holds two lines of text; for example:

Program to Destroy the World
Press Enter to explode:
  • A string variable in C is really a character array.

  • You can assign a value to a char array when it’s created, similarly to the way you initialize any variable when it’s created. The format looks like this:

    char string[] = "text";

    In the preceding line, string is the name of the char array, and text is the string assigned to that array.

  • You can assign a value to a string, or char array, only when it’s declared in the code. You cannot reassign or change that value later by using a direct statement, such as

    prompt = "This is just wrong.";

    Changing a string is possible in C, but you need to know more about arrays, string functions, and especially pointers before you make the attempt.