Intermediate · C PROGRAMMING

Strings and termination

What you will learn

Recognize a C string as characters ending with a null character.

Understand the concept

A string literal used to initialize an array includes a terminating null byte. strlen counts characters before that byte, while sizeof the array includes all its storage. The string.h header declares strlen.

Read the example

The complete program appears below. Read it first, predict the output, then run it.

Expected output

Length: 3, storage: 4

Practise

Change the text to Pune. Predict both numbers before running.

Common mistake

Reserve space for the null terminator. A character array without a terminator is not safe to pass to functions expecting a C string.

Lesson discussion

Log in to participate.

#include <stdio.h>
#include <string.h>

int main(void) {
    char name[] = "TCS";
    printf("Length: %zu, storage: %zu\n", strlen(name), sizeof name);
    return 0;
}
PRACTICE LAB

Read. Edit. Run.

C source · .c

Experiment with the program below. Your code and input are sent to the selected compiler only when you run it.

Tab indents · Shift+Tab unindents · Esc then Tab leaves the editor · Ctrl/Cmd+Enter runs · Ctrl/Cmd+S saves a draft

Changes save automatically to your account.

Input / output example

Example input
No input required.
Expected output for the original program
Length: 3, storage: 4
Output will appear here.

Log in to save your progress

Ready when you are

Need help with your laptop or computer?

Send us the model and fault details. Start your repair request online or contact TCS Pune directly.

WA