Skip to content

Beginner · Strings in C · topic 16 of 60 · 25 min

Strings are char arrays

Explanation

C has no string type. A string is an array of char that ends with the null character '\0', which marks where the text stops. char s[] = "Hi"; makes an array of 3 chars: H, i and \0. String literals are read-only, so changing one through a pointer is undefined behaviour. Print strings with %s.

Text in C

Most languages have a built-in string type that knows its own length. C does not. A C string is just a sequence of char values in memory, followed by a special char with value 0, written '\0' and called the null terminator. Every string function walks along the characters until it reaches that 0.

output
char city[] = "Pune";

index:   0     1     2     3     4
value:  'P'   'u'   'n'   'e'   '\0'
sizeof city = 5  (4 letters + the terminator)
strlen(city) = 4 (the terminator is not counted)
The compiler adds the \0 automatically for a string literal.
c
#include <stdio.h>
#include <string.h>

int main(void) {
    char name[20] = "Asha";              /* 20 bytes reserved; "Asha\0" uses the first 5 */
    printf("%s has %zu letters\n", name, strlen(name));   /* Asha has 4 letters */
    name[0] = 'U';                       /* arrays are writable */
    printf("%s\n", name);                /* Usha */
    char letters[] = {'H', 'i', '\0'};   /* the same as "Hi" */
    printf("%s\n", letters);
    return 0;
}

Arrays versus pointers to literals

c
char a[] = "Delhi";        /* an ARRAY initialised with a copy of the text: writable */
const char *p = "Delhi";   /* a POINTER to a string literal stored in read-only memory */
a[0] = 'd';                /* fine */
/* p[0] = 'd';  */         /* undefined behaviour (usually a crash): literals are read-only */
Declare pointers to literals as const char * so the compiler stops you from writing to them.

Characters versus strings

'A' (single quotes) is one char, a small integer (65 in ASCII). "A" (double quotes) is a string: an array of two chars, 'A' and '\0'. printf("%c", 'A') prints a char; printf("%s", "A") prints a string. Mixing them up (printf("%s", 'A')) is undefined behaviour and usually crashes.

Comparing and assigning

You cannot assign an array with =, and == on two strings compares their ADDRESSES, not their text. Use strcpy/snprintf to copy and strcmp to compare (next topic).

c
char a[10] = "chai", b[10] = "chai";
if (a == b) { }               /* false: two different arrays at different addresses */
if (strcmp(a, b) == 0) { }    /* true: same text */
Careful: Forgetting room for the terminator is a classic bug: char code[6] = "560001"; has exactly 6 characters and NO \0 (C allows this initialisation), so printf("%s", code) keeps reading past the array into other memory. Always size arrays as (maximum length + 1).
Think of it like this: A C string is like a train of coaches with no coach counter: the only way to know where the train ends is the brake van at the back (the \0). If the brake van is missing, the station master keeps counting coaches that belong to the next train on the track.
Tip: When you print a string and see strange extra characters at the end, the first suspect is a missing \0.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Strings are char arrays · 1/6

Strings in C

In this lesson you will see how C stores text.

Prefer a video by a teacher? Find free videos on “c strings null terminator char array string literal explained” on YouTube ↗

In real life: Storing PIN codes as text

An address-label printer stores Indian PIN codes as strings, not ints, so codes are always 6 characters (and the program never treats them as numbers to add). Each array is sized 7: six digits plus the terminator.

c
char pin[7] = "560001";        /* 6 digits + '\0' */
printf("PIN: %s (%zu digits)\n", pin, strlen(pin));   /* PIN: 560001 (6 digits) */

Practice (0/3 done)

Task 1 · Question

What does this print? char s[] = "Hello"; printf("%zu %zu\n", sizeof s, strlen(s));

Task 2 · Question

Which line has undefined behaviour? 1: char a[] = "tea"; 2: a[0] = 'T'; 3: char *p = "tea"; 4: p[0] = 'T';

Task 3 · Code · Javascript

Simulate how C finds the end of a string: write cStrlen(bytes) where bytes is an array of character codes (numbers) as they sit in memory. Return how many bytes come before the first 0 (the terminator). If there is no 0 at all, return -1 (in C this would read past the array).

Quick quiz

Question 1

1.What marks the end of a C string?

Question 2

2.How many bytes does "UPI" occupy as a string literal?

Question 3

3.char a[] = "x", b[] = "x"; What does a == b compare?

Question 4

4.What is '7' (with single quotes)?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What marks the end of a C string?

Answer: The null character \0

Every string function stops at \0.

How many bytes does "UPI" occupy as a string literal?

Answer: 4

3 letters + the terminator.

char a[] = "x", b[] = "x"; What does a == b compare?

Answer: The addresses of the two arrays

Use strcmp for text.

What is '7' (with single quotes)?

Answer: A char whose code is 55 in ASCII

Characters are small integers.

Where does an array NOT decay to a pointer?Related

Answer: In sizeof a

sizeof (and &a) see the whole array.

From Pointers and arrays

let s = 'hi'; s.toUpperCase(); console.log(s); What is printed?Related

Answer: 'hi'

Strings are immutable; the result of toUpperCase was thrown away.

From Strings and template literals

What marks the end of a C string?Related

Answer: The null character '\0'

C functions read characters until they meet '\0'.

From Text: C strings and std::string

Which function signature accepts both a &String and a literal?Related

Answer: fn f(s: &str)

&String coerces to &str automatically, and literals already are &str.

From Slices and strings

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 4 more topics in “Strings in C” before its exam: The <string.h> functions, Reading strings safely, Characters and <ctype.h>, Buffer overflows and safe string handling.
  2. Module 4 exam: Strings in C · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Pointers. 60 topics left in the course before the final exam.

← Previous: 2D arrays and classic array algorithms