2.13. Strings

  • A string in an array of char ending with \0.
  • When using printf() and scanf(), use the %s format statement for strings.

2.13.1. Initializing a string

  • char s[50]; Allocates memory for a string, but no assignment is made.
  • char s[] = "abc"; Allocates just enough memory for the string. In this case, 4 char values are allocated (three actual characters and one for the null terminator \0).
  • char *p = "abc"; Only the pointer is in the stack. The pointer is set to memory in the text area (read only) of the program which holds the string “abc”, which is a constant.

Note

Strings will be covered in much more detail later in the semester. For now, it is enough to note how to allocate, read and print strings.

It may be worth noting now that the sprintf() function from the string library may be used to assign a string to an array of characters in the body of a program. See sprintf(). The sprintf() function is needed to set the contents of a string because strings are not a fundamental data type in C. Another consequence of this is the need to use the strcmp() function to make relational comparisons of strings. See strcmp().