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 Literals are
const char
arrays. - String variables are Dynamically Allocated or declared with a
str[LENGTH]
. - In order to do various Functions with Strings, we have to use the string.h Library.
- In C, strings end with a Null Terminator character
\0
which indicates the end of the string. This is used toprintf
or traverse through strings. - C compilers parse two adjacent strings as a single String Literal constant:
Where are String Literals like
Hello World!
stored in C programs?They are not stored in either the Execution Stack or the Memory Heap, they are in Non-overlapping Read-only Memory, allocated during Compiler's Preprocessing time.
- When multiple variables reference it, they are redirected to the same memory address.
- See String Literal.
String Variables
- They need to be declared like
char str[]
instead ofchar *str
. - We typically set a
#define MAX_LEN x
then dochar 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 aconst 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
- C Programming, A Modern Approach, 2nd Edition, Chapter 13.1-13.2