Skip to content

Strings are char arrays

Read · 1 of 5

Characters with a stop sign

char name[20] = "Asha"; stores 'A', 's', 'h', 'a' and then a hidden '\0' (the null character) that marks the end. Every string function stops at it, so the array needs room for one extra char.

scanf("%s", name); reads one word (no & needed: an array name is already an address). To read a whole line with spaces, use fgets(line, sizeof line, stdin);, which keeps the \n at the end.

Read this lesson as text

How C stores text, and how to read a word or a whole line.

Characters with a stop sign

char name[20] = "Asha"; stores 'A', 's', 'h', 'a' and then a hidden '\0' (the null character) that marks the end. Every string function stops at it, so the array needs room for one extra char.

scanf("%s", name); reads one word (no & needed: an array name is already an address). To read a whole line with spaces, use fgets(line, sizeof line, stdin);, which keeps the \n at the end.

Walking to the '\0'

#include <stdio.h>

int main() {
    char s[10] = "cat";
    int len = 0;
    while (s[len] != '\0') len++;
    printf("%s has %d letters, last is %c\n", s, len, s[len - 1]);
    return 0;
}
  1. Line 4: Memory holds c, a, t, \0, and the rest of the 10 chars are unused.
  2. Line 6: Count chars until the '\0': c, a, t, so len stops at 3.
  3. Line 7: %s prints the text up to the '\0'.

Cut short

#include <stdio.h>

int main() {
    char s[] = "hello";
    s[2] = '\0';
    printf("[%s]\n", s);
    return 0;
}

What does this print?

  • [he]
  • [helo]
  • [hello]
Show the answer

[he] printf stops at the first '\0'. Putting one at position 2 ends the string after "he".

Exercise: Greet by name

Read a first name (one word, under 30 letters) and print Hello, <name>!

Exercise: Initials

Read a full name on one line (up to 100 characters, words separated by single spaces). Print the initials in capitals: asha r patil → ARP.

A lowercase letter c becomes capital with c - 'a' + 'A'.