Strings
A string is an array of characters (char
s), terminated by the null terminator character, '\0'
.
In general, the type of a string in C is char*
.
String Literals
We have seen string literals so far—a sequence of characters written down in quotation marks, such as "Hello World\n"
.
The type of a string literal is const char*
, so this is valid C:
const char* str = "Hello World\n";
The const
shows up here because the characters in a string literal cannot be modified.
Mutable Strings
A mutable string has type char*
, without the const
.
How can you declare a mutable string with a string literal, if string literals are always const
?
Here’s a trick you can use:
remember that, in C, an array is like a pointer to its first element.
So let’s declare the string as an array and give it an initializer:
char str[] = "Hello World\n";
This code behaves exactly as if we wrote:
char str[] = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '\n', '\0'};
It declares a variable str
which is an array of 13 characters (remember that the size of an array may be implicit if we provide an initializer from which the compiler can determine the size), and initializes it by copying the characters of the string "Hello World\n"
(including the null terminator) into that array.
String Equality
The expression str1 == str2
doesn’t check whether str1
and str2
are the same string!
Remember, since both of these have a pointer type (char*
), C will just compare the pointers.
Instead, if you want to check whether two strings contain equal contents, you will need to use a function like strcmp
from the string.h
header.
String Copying
Similarly, an assignment like str1 = str2;
does not copy strings!
It just just does pointer assignment, so now str1
points to the same region of memory as str2
.
Use a function like strcpy
if you need to copy characters.