Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

1Learning Outcomes

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).

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:

To read about any standard string function, we recomment the manual pages (“man pages”). You can type the following into a terminal:

man strlen

Consider 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
5
int 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.

Footnotes
  1. See glibc for a more practical, efficient implementation of strlen.

  2. 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.