1Learning Outcomes¶
Differentiate between an array of characters and a C string.
Know how to use standard C library functions in
string.h.
No video.
2C Strings vs. char arrays¶
A C string (i.e., “string”) is just an array of characters, followed by a null terminator. A null terminator is the byte of all 0’s, i.e., the ‘\0’ character. The ASCII value of the null terminator is 0.
The null terminator lets us determine the length of a C string from just a pointer to the beginning of the string.
When you make a character array, you should terminate the array with a null terminator. For example, the code
char my_str[] = {'e', 'x', 'a', 'm', 'p', 'l', 'e', '\0'};declares an 8-byte char array on the stack, then initializes the array with the 8 specified chars. Read about the stack in another section.
If you are using double quotes (") to create a string, the null terminator is implicitly added, so you should not add it yourself. For example the code
char *my_str = "example";declares a pointer to the 8-byte string literal (which includes the null terminator).
Show Answer
No. While arr is a char array, it does not end in a null terminator and by definition is not a C string.
3<string.h>¶
C strings have functions in the C standard library, imported via the header <string.h>. See Wikibooks for descriptions of commonly used <string.h> functions. Here are the two that you may encounter in this course:
strlen: computes the length of a string by counting the number of characters before a null terminatorstrcpy: copies a string from one memory location to another, one character at a time until it reaches a null terminator (the null terminator is copied as well).
To read about any standard string function, we recomment the manual pages (“man pages”). You can type the following into a terminal:
man strlenConsider the following code, which is a reasonable implementation of strlen[1], the standard C library function that computes the length of a string, minus the null terminator.
1 2 3 4 5int strlen(char s[]) { size_t n = 0; while (*(s++) != 0) { n++; } return n; }
4String literals¶
Strings created with the following syntax are read only, or immutable. After this *string literal is created, a C program cannot dereference my_immutable_str and read its data, but it cannot alter the value of the string during execution.
char *my_immutable_str = "Hello";By contrast, the below declaration creates a string that is mutable:
char my_str[] = "hello";These immutable strings prevent This means that you cannot alter the value of the string after you have created it. In other words, it is immutable. char *my_str = “Hello”; However, a string created using the following syntax is mutable.
String literals are located in a read-only data segment, which we don’t discuss in this class. Read more in the footnotes when we discuss memory layout.