bhylu.com

Advertisements

C Strings

Distinguish a text length from an array capacity and leave room for its terminating zero byte.

How it works

A C string is a sequence of nonzero char values followed by a zero byte. The terminator is part of storage but not part of the logical text length. A character array is not automatically a string: it must contain that terminator within its accessible bounds before a string function can read it. Literal initialization normally includes it for you. char arrays hold bytes in an execution encoding; a visible Unicode character can occupy more than one byte, so byte indexing is not a complete text-editing model.

Run it locally

Use a hosted C17 compiler in a separate lab folder. The command assumes a driver named cc; substitute gcc, clang or zig cc as appropriate. C does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed for these C programs.

cc -std=c17 -Wall -Wextra -Wpedantic -Werror terminated-text.c -o lesson

On Windows, use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Math-library linking differs by toolchain; GCC on many Unix systems needs -lm after the source.

Download the complete C source. File-writing labs must run in an empty private directory, away from existing reports.

Example

C17 · terminated-text.c

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

int main(void) {
    char label[] = "Plot-7";
    printf("Length: %zu; capacity: %zu\n", strlen(label), sizeof label);
    label[5] = '8';
    printf("%s\n", label);
    printf("Terminated: %d\n", label[6] == '\0');
    return 0;
}

Expected result

Length: 6; capacity: 7
Plot-8
Terminated: 1

strlen counts the six bytes before the terminator. sizeof measures the seven-byte array object. Replacing the final digit preserves the terminator at index six. This is mutable array storage; a pointer to a string literal would not give permission to modify the literal. A bounded input operation must reserve the same extra byte when filling this kind of array.

For language and library rules, consult the WG14 C working group and its public C11 committee draft, which describes the core facilities used here; C17 incorporates corrections. Check your compiler and runtime documentation for implementation details.

Advertisements