Skip to content
Circuit

String Length in C

Strings

Count characters in a null-terminated string and distinguish length from capacity.

Complete program

#include <stdio.h>

int main(void) {
    char text[] = "Circuit";
    size_t length = 0;
    while (text[length] != '\0') ++length;
    printf("Length: %zu\n", length);
    printf("Array bytes: %zu\n", sizeof text);
    return 0;
}

Try in Circuit →

Opens a new program without replacing your saved code. Press Run when you are ready.

How it works

A string ends at its first null character, which is a byte with value zero. The terminating byte takes storage but is not counted as part of the string length.

The compiler includes the terminator in this initialized array. For arbitrary input, ensure a terminator exists within the buffer before scanning. This byte count is not a general count of human-readable characters in UTF-8 text.

Expected output

Length: 7
Array bytes: 8

Concepts to practice

  • Character arrays
  • Null terminator
  • Length vs capacity

Predict a different input or change one value, then compare the result with your prediction. Keep changes within the documented bounds and read warnings before trusting an answer.