Skip to content

Module 5 · Arrays and Strings — topic 3 of 3

Strings

A C string is an array of char ending with the null character '\0'. Learn how strings are stored, read and printed, and how to use strlen, strcpy, strcat, strcmp and their safer bounded versions.

Beginner 18 min read·Lesson 21 of 37 in C Programming

Learning objectives

  • Declare and initialise strings as char arrays
  • Use <string.h> functions correctly
  • Read strings safely with fgets and avoid buffer overflows

Definition

A string in C is a contiguous sequence of characters terminated by and including the first null character ('\0'). String literals are arrays of char with static storage duration; functions in <string.h> operate on strings through pointers to their first character.

Introduction

C has no built-in string type. Text is stored in a char array, and the end of the text is marked by a zero byte, '\0'. Every string function relies on finding that terminator.

This design is simple and fast, but it is also behind many of the most famous security vulnerabilities in history: copy a 30-character name into a 20-character array and the extra bytes overwrite whatever lies next in memory.

Why it matters

Text processing — names, commands, files, network messages — is everywhere. Knowing how C strings work is required for file handling, command-line arguments and almost every project in this course.

String questions (strlen vs sizeof, comparing with ==, reversing, palindromes, counting vowels) are among the most common in C interviews.

Detailed explanation

char name[] = "Ravi"; creates a 5-byte array: 'R' 'a' 'v' 'i' '\0'. char name[20] = "Ravi"; reserves 20 bytes; the unused ones are zero.

strlen(s) counts characters before the terminator (4 for "Ravi"). sizeof name gives the array size in bytes (5 or 20), and only works on arrays.

Strings cannot be assigned or compared with operators. Use strcpy(dest, src) to copy, strcat(dest, src) to append, and strcmp(a, b) to compare: it returns 0 if equal, a negative value if a sorts first, positive otherwise.

Bounded versions limit how much is written: snprintf(dest, size, "%s", src) always null-terminates and is the safest general tool. strncpy does not add a terminator when the source is too long, so it must be used carefully.

For input, scanf("%19s", buf) reads one word. To read a whole line including spaces, use fgets(buf, sizeof buf, stdin), which keeps the newline; remove it with buf[strcspn(buf, "\n")] = '\0';.

FunctionPurposeNote
strlen(s)length without '\0'returns size_t
strcpy(d, s)copy s into dd must be large enough
strcat(d, s)append s to dd must have room
strcmp(a, b)compare0 means equal
strchr(s, c)find a characterreturns pointer or NULL
strstr(s, t)find a substringreturns pointer or NULL
snprintf(d, n, ...)formatted, bounded writealways terminates if n > 0

Syntax

C
char s1[] = "hello"; /* 6 bytes incl. '\0' */
char s2[32];
snprintf(s2, sizeof s2, "%s, world", s1);
size_t len = strlen(s2);
if (strcmp(s1, "hello") == 0) { /* equal */ }
fgets(s2, sizeof s2, stdin); /* read a line safely */
  • Always leave room for the terminator: n characters need n + 1 bytes.
  • "A" is a string (2 bytes); 'A' is a character (an int).
  • Include <string.h> for the string functions.

Code examples

Length vs size

C
#include <stdio.h>
#include <string.h>
int main(void) {
char city[20] = "Hyderabad";
printf("strlen = %zu\n", strlen(city));
printf("sizeof = %zu\n", sizeof city);
printf("last char = %c\n", city[strlen(city) - 1]);
return 0;
}
Output
strlen = 9
sizeof = 20
last char = d

Copy, append, compare

C
#include <stdio.h>
#include <string.h>
int main(void) {
char full[40];
strcpy(full, "Ada");
strcat(full, " Lovelace");
printf("%s (%zu chars)\n", full, strlen(full));
printf("%d\n", strcmp("apple", "apple"));
printf("%d\n", strcmp("apple", "banana") < 0);
return 0;
}
Output
Ada Lovelace (12 chars)
0
1

More examples

Reading a line and analysing it

C
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int is_palindrome(const char *s) {
size_t i = 0, j = strlen(s);
if (j == 0) return 1;
j--;
while (i < j) {
while (i < j && !isalnum((unsigned char)s[i])) i++;
while (i < j && !isalnum((unsigned char)s[j])) j--;
if (tolower((unsigned char)s[i]) != tolower((unsigned char)s[j])) return 0;
i++;
j--;
}
return 1;
}
int main(void) {
char line[100];
printf("Enter a sentence: ");
if (!fgets(line, sizeof line, stdin)) return 1;
line[strcspn(line, "\n")] = '\0'; /* strip the newline */
int vowels = 0, words = 0, in_word = 0;
for (size_t i = 0; line[i] != '\0'; i++) {
char c = (char)tolower((unsigned char)line[i]);
if (strchr("aeiou", c) && c != '\0') vowels++;
if (isspace((unsigned char)line[i])) in_word = 0;
else if (!in_word) { in_word = 1; words++; }
}
printf("\n\"%s\"\n", line);
printf("%d words, %d vowels\n", words, vowels);
printf("palindrome: %s\n", is_palindrome(line) ? "yes" : "no");
return 0;
}
Input
Never odd or even
Output
Enter a sentence: 
"Never odd or even"
4 words, 6 vowels
palindrome: yes

Step-by-step explanation

  • fgets reads the whole line, including spaces, but never more than 99 characters plus the terminator.
  • line[strcspn(line, "\n")] = '\0'; replaces the newline that fgets keeps.
  • The loop stops at '\0' — the standard way to walk a C string.
  • A word starts each time a non-space character follows a space (the in_word flag).
  • is_palindrome compares from both ends, skipping spaces and ignoring case with tolower.
  • Casting to unsigned char before calling <ctype.h> functions avoids undefined behaviour for negative char values.

Expected output

Running “Reading a line and analysing it” with the sample input shown prints exactly:

TextInput
Never odd or even
TextOutput
Enter a sentence:
"Never odd or even"
4 words, 6 vowels
palindrome: yes

Practical applications

  • Command interpreters split input lines into words.
  • Web servers parse HTTP headers, which are null-terminated strings in C implementations.
  • Buffer overflows from strcpy and gets caused real attacks such as the 1988 Morris worm.

Best practices

  • Size buffers generously and always pass their size to input functions.
  • Prefer snprintf and fgets over strcpy, strcat and gets.
  • Declare pointers to literals as const char *.

Common mistakes

Comparing strings with ==

Avoid

if (password == "secret") { /* ... */ }

Prefer

if (strcmp(password, "secret") == 0) { /* ... */ }

== compares addresses, not characters. Two equal strings at different addresses compare unequal.

No room for the terminator

Avoid

char code[4] = "ABCD";

Prefer

char code[5] = "ABCD";

"ABCD" needs 5 bytes. With 4, C drops the terminator (legal in C, an error in C++) and string functions read past the end.

Modifying a string literal

Avoid

char *s = "hello";
s[0] = 'H';

Prefer

char s[] = "hello";
s[0] = 'H';

A pointer to a literal may point into read-only memory; writing to it is undefined behaviour and often crashes. An array is a modifiable copy.

Important notes

  • gets was removed in C11 because it cannot be used safely. Some compilers still provide it with a warning — never use it.
  • strlen walks the whole string each call; calling it in a loop condition (i < strlen(s)) makes the loop O(n²). Store the length in a variable.

Key takeaways

  • C strings are char arrays ending with '\0'.
  • Use strlen for length, strcmp for comparison, snprintf/fgets for safe writing and reading.
  • Always reserve one extra byte for the terminator.

Try it yourself

  1. 1
    Write your own my_strlen and my_strcpy using loops and compare their results with the library versions.
  2. 2
    Read a line and print it with each word's first letter capitalised.
  3. 3
    Count the frequency of each letter in a sentence (ignore case).

Finished reading? Mark it complete to update your dashboard.

Suggested practice

12 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerHow many bytes does the string literal "code" occupy?
  • BeginnerWhy is `if (name == "admin")` wrong for checking a string?
Practise this topic