Created: 2023-01-15 14:12
Status: #concept
Subject: Programming
Tags: C C Array C Data Type Character String Literal string.h

String

Definition

They are a sequence or "string" of Characters enclosed in double quotation marks. ex: "When you come to a fork in the road, take it."

Strings are just char C Arrays.

String Representation in C.png

String Variables

They are just Character C Arrays with a Null Terminator to determine the end of the string.

  • They need to be declared like char str[] instead of char *str.
  • We typically set a #define MAX_LEN x then do char str[x+1] to indicate a string and leave space for the '\0' character.

If we do not have the Null Terminator '\0' character when using a string variable in string.h functions, it will not work as intended.

  • the '\0' character allows us to signal a function to stop traversing the string, otherwise it will segfault.

char date[8] = "June 14"; // 7 characters, but with the automatically placed \0
char date[] = "June 14"; // equivalent
char date[8] = {'J', 'u', 'n', 'e', ' ', '1', '4', '\0'}; // equivalent

char date[8] = "May 1"; // has 3 extra spaces
char date[8] = {'M', 'a', 'y', ' ', '1', '\0', '\0', '\0'}; // equivalent

Common Pitfalls between date[] & *date

String Variables can be modified, String Literals cannot.

  • The characters we store in date[] can be modified after it is declared, like elements in an array.
  • *date's elements cannot be modified because it points to a String Literal which is a const char *.

date is an Array Name; while the other date is a pointer variable.

  • For the array version [], date is a an array pointer to the first element of the array.
  • For the pointer version *, date is a Pointer Variable and can point to other objects when assigned.

References