C:C Strings: Null-Terminated Character Arrays (char[])
C•Strings

C Strings: Null-Terminated Character Arrays (char[])

In C, strings are simply contiguous character arrays ending with the null terminator character \0.

Syntax

char str[] = "Hello"; size_t len = strlen(str);

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
\0Null TerminatorByte value 0 signaling the end of the string in memory.
strlenFunctionCounts characters in string excluding the null terminator.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing C locally:

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

int main(void) {
    char greeting[32] = "Hello";
    const char* target = "Compilra";

    // String concatenation
    strcat(greeting, ", ");
    strcat(greeting, target);
    strcat(greeting, "!");

    printf("Full String: %s\n", greeting);
    printf("Length:      %zu characters\n", strlen(greeting));
    printf("Buffer Size: %zu bytes\n", sizeof(greeting));

    // String comparison
    int comparison = strcmp(target, "Compilra");
    printf("strcmp match: %s\n", (comparison == 0 ? "EXACT MATCH" : "DIFFERENT"));

    return 0;
}
Expected Output:
Full String: Hello, Compilra!
Length:      17 characters
Buffer Size: 32 bytes
strcmp match: EXACT MATCH

How It Works: Step-by-Step

  • Lines 5-6: Allocates buffer greeting and pointer target.
  • Lines 9-11: strcat appends text, updating the null terminator position.
  • Line 18: strcmp returns 0 when two strings have identical characters.

Key Concepts

  • strlen() counts characters up to the \0 byte; sizeof() returns total buffer size.
  • strcmp() returns 0 for equal strings, negative if str1 < str2, positive if str1 > str2.
  • Always reserve at least 1 extra byte for the null terminator (size >= length + 1).

Common Mistake: Comparing C strings with == instead of strcmp

In C, == compares memory pointer addresses, NOT the characters inside the strings.

❌ Incorrect
if (str == "Compilra") { /* Bug: compares pointer addresses! */ }
✅ Correct
if (strcmp(str, "Compilra") == 0) { /* Compares string characters */ }

Related C Tutorials & Compiler

Run and test C on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C Online Compiler