100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
C

Strings in C

Master C strings: null-terminated char arrays, string literals vs char arrays, key string.h functions, and buffer-overflow pitfalls.

Arrays & StringsBeginner15 min readJul 7, 2026
Analogies

1. Introduction

C has no dedicated built-in string data type. Instead, a 'string' in C is simply a sequence of characters stored in a char array, terminated by a special sentinel character called the null character, '\0' (numeric value 0). This null terminator marks the end of the string's content and tells string-handling functions where to stop reading, since the array itself may be larger than the text it holds.

🏏

Cricket analogy: A scoreboard display of '180' stored in a wider digital board that can show up to 3 digits uses a 'stop' signal after the last digit — like C's '\0' — so the display knows not to show trailing blank segments as part of the score.

Because strings are just char arrays under the hood, they inherit all the rules of arrays covered previously — contiguous memory, zero-based indexing, and (crucially) no automatic bounds checking. Almost all standard string manipulation in C is done through functions declared in the <string.h> header, such as strlen, strcpy, strcat, and strcmp.

🏏

Cricket analogy: Since a player's name string is just a char array, indexing name[0] for the first letter follows the same zero-based rules as accessing batsman[0] in a lineup array — and functions like strcmp are needed to alphabetically sort the team roster, just as strcmp compares two strings.

2. Syntax

c
#include <string.h>

// Declaring a string as a char array with a literal initializer
char str1[] = "Hello";          // size automatically becomes 6 (5 chars + '\0')

// Declaring a string with an explicit size
char str2[20] = "Hello";        // remaining bytes are zero-filled

// Pointer to a string literal (read-only)
const char *str3 = "Hello";

// Character-by-character initialization (must add '\0' manually)
char str4[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

3. Explanation

A C string's length as reported by strlen() counts only the visible characters, not the null terminator itself. However, the storage allocated for the string must always be at least strlen(s) + 1 bytes to make room for that terminating '\0'. Forgetting to account for this extra byte is one of the most frequent sources of bugs in C string handling.

🏏

Cricket analogy: strlen('Kohli') returns 5, counting only the letters, not a trailing marker — but the buffer holding the name must be sized 6, just as a nameplate must be cut slightly larger than the printed letters to leave room for the mounting edge.

String Literals vs Char Arrays

There is an important distinction between char str[] = "Hello"; and const char *ptr = "Hello";. In the first form, "Hello" is used to initialize a mutable array; the characters are copied into str's own stack (or static) storage, and individual characters can be modified afterward (str[0] = 'J'; is legal). In the second form, ptr points directly at a string literal, which the compiler typically places in read-only memory; attempting to modify *ptr (e.g. ptr[0] = 'J';) is undefined behavior and often crashes with a segmentation fault on common platforms. As a best practice, string literals accessed through a pointer should always be declared const char * to make this immutability explicit and let the compiler catch accidental writes.

🏏

Cricket analogy: Writing a player's name in chalk on a reusable scoreboard (char str[] = 'Kohli') lets you erase and rewrite a letter anytime, but a name engraved on a permanent trophy plaque (const char *ptr = 'Kohli') can't be altered — trying to chisel a new letter into it risks cracking the plaque, like undefined behavior.

c
char mutable[] = "Hello";
mutable[0] = 'J';           // OK: modifies the array's own copy -> "Jello"

const char *literal = "Hello";
// literal[0] = 'J';        // undefined behavior: attempts to modify a string literal

Common string.h Functions

The <string.h> header provides the core toolkit for C string manipulation. strlen(const char *s) scans forward from s until it finds '\0' and returns the count of characters before it (an unsigned size_t, not including the terminator). strcpy(char *dest, const char *src) copies characters from src into dest, including the terminating null byte, and assumes dest has enough space — it performs no bounds checking whatsoever. strcat(char *dest, const char *src) appends src onto the end of dest (locating the end of dest via its existing null terminator) and again assumes sufficient space in dest. strcmp(const char *s1, const char *s2) performs a lexicographic (dictionary-order) comparison and returns 0 if the strings are equal, a negative value if s1 sorts before s2, and a positive value if s1 sorts after s2.

🏏

Cricket analogy: strlen counts a player's name length like counting letters on a jersey; strcpy copies a new sponsor logo onto a jersey template assuming it fits (no bounds checking); strcat appends a nickname after the surname; strcmp checks if two entered team names match exactly, like verifying a toss call.

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

int main(void) {
    char greeting[50] = "Hello";
    char name[] = ", World!";

    printf("Length: %zu\n", strlen(greeting));   // 5

    strcat(greeting, name);                       // greeting becomes "Hello, World!"
    printf("After strcat: %s\n", greeting);

    char copy[50];
    strcpy(copy, greeting);
    printf("Copy: %s\n", copy);

    if (strcmp(greeting, copy) == 0) {
        printf("greeting and copy are equal\n");
    }
    return 0;
}

Tip: strcmp returns an int whose sign (not magnitude) matters — do not assume it returns -1, 0, or 1 exactly. Always compare the result to 0 (e.g., if (strcmp(a, b) == 0)) rather than checking for a specific value like -1.

Buffer Overflow Pitfalls: strcpy vs strncpy

strcpy and strcat are notoriously unsafe because they copy or append data with no awareness of the destination buffer's actual capacity. If src is longer than the space available in dest, these functions will happily write past the end of the destination array — a classic buffer overflow. This is undefined behavior that can corrupt adjacent stack variables, overwrite a function's saved return address, and has historically been one of the most exploited categories of security vulnerabilities in C programs (e.g., stack-smashing attacks).

🏏

Cricket analogy: strcpy blindly copying a sponsor's overly long name onto a jersey template sized for a short name is like a tailor stitching text that overruns the jersey and bleeds onto the shorts — a buffer overflow that corrupts what's 'adjacent,' just as stack-smashing corrupts nearby memory.

A safer alternative is strncpy(char *dest, const char *src, size_t n), which copies at most n characters from src into dest, preventing the function itself from writing past n bytes. However, strncpy has its own gotcha: if src is longer than or equal to n characters, strncpy does NOT null-terminate dest — you must manually ensure termination, typically by setting dest[n-1] = '\0' after the call. Similarly, strncat(dest, src, n) limits how many characters are appended from src (though the total dest buffer must still be large enough, since strncat does properly null-terminate the result). Modern code should always know the destination buffer size and pass it explicitly to these bounded variants.

🏏

Cricket analogy: strncpy limiting a name copy to n=10 characters is like a scoreboard operator capping a long surname at 10 letters — but if the name is exactly 10 or longer, the operator must manually add a period at the end, or the display keeps bleeding into the next field; strncat, appending a nickname, properly caps and terminates it, like adding a name with an automatic full stop.

Warning: char buf[6]; strcpy(buf, "HelloWorld"); is undefined behavior — "HelloWorld" plus its null terminator needs 11 bytes, but buf only has 6, so strcpy writes 5 bytes past the end of buf. This can silently corrupt other variables or crash the program. Prefer strncpy(buf, src, sizeof(buf) - 1); buf[sizeof(buf) - 1] = '\0'; to guarantee both a bounded copy and proper null-termination.

c
char buf[6];

// UNSAFE: no bounds checking, overflows buf
strcpy(buf, "HelloWorld");

// SAFER: bounded copy, but must manually ensure null-termination
strncpy(buf, "HelloWorld", sizeof(buf) - 1);
buf[sizeof(buf) - 1] = '\0';   // guarantees termination even if src was truncated
printf("%s\n", buf);            // prints "Hello" (truncated, but safe)

4. Example

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

int main(void) {
    char first[20] = "Data";
    char second[20] = "Structures";
    char result[41]; // enough for both strings + separator + '\0'

    // Safely build "Data Structures"
    strncpy(result, first, sizeof(result) - 1);
    result[sizeof(result) - 1] = '\0';

    strncat(result, " ", sizeof(result) - strlen(result) - 1);
    strncat(result, second, sizeof(result) - strlen(result) - 1);

    printf("Combined: %s\n", result);
    printf("Length: %zu\n", strlen(result));

    if (strcmp(first, "Data") == 0) {
        printf("first is exactly \"Data\"\n");
    }

    return 0;
}

5. Output

text
Combined: Data Structures
Length: 15
first is exactly "Data"

6. Key Takeaways

  • A C string is a char array terminated by the null character '\0'; strlen() counts characters excluding this terminator.
  • A buffer of n meaningful characters requires at least n + 1 bytes of storage to hold the trailing '\0'.
  • char str[] = "text"; creates a mutable, independently-owned copy; const char *p = "text"; points to a read-only string literal that must not be modified.
  • strlen, strcpy, strcat, and strcmp are the core string.h functions; strcmp returns 0 for equal strings, not true/false.
  • strcpy and strcat perform no destination bounds checking and are common sources of buffer overflows.
  • strncpy bounds the number of bytes copied but does not guarantee null-termination if the source is too long — you must terminate manually.
  • Always know your destination buffer's size and prefer bounded functions (strncpy/strncat) with explicit manual null-termination for safety.

Practice what you learned

Was this page helpful?

Topics covered

#CProgrammingStudyNotes#Programming#StringsInC#Strings#Syntax#Explanation#String#StudyNotes#SkillVeris#ExamPrep

Frequently Asked Questions

21 categories · pick one to explore

Where can I get free study notes for programming and tech subjects?
SkillVeris offers completely free study notes covering programming and tech subjects, with no signup fees or paywalls. The notes are structured by course and topic, written for quick understanding, and enriched with the Learn Through Hobbies analogy method, so you can revise concepts through cricket, music, gaming, cooking and more.
Are SkillVeris study notes good for exam revision?
Yes, the study notes are designed for efficient revision: each topic answers its heading immediately, keeps explanations concise, and links to related glossary terms and cheat sheets. Students preparing for university exams or certification tests use them as quick revision notes because they distil concepts without the padding of full textbooks.
What subjects do the free study notes cover?
The study notes span the platform's main domains, including AI and machine learning, Python and programming, web development, DevOps, cloud, security and databases. Coverage mirrors the 37 live courses, so notes exist for the topics you are actually studying, and new note sets are added as courses launch.
How are SkillVeris study notes different from regular textbooks?
The notes are answer-first, concise and free, whereas textbooks are long and often expensive. Each section explains one concept directly, then reinforces it through selectable hobby analogies like cricket or cooking. Notes also cross-link to the glossary, blog and cheat sheets, letting you jump to related material instantly instead of flipping pages.
Can I use the developer study material without creating an account?
The study notes are free to access, and SkillVeris does not charge anything for its developer study material at any point. Browsing notes is straightforward from the Study Notes section, and if you want progress tracking, certificates and AI Mentor conversations tied to your learning, a free account unlocks those extras.
Do the study notes explain concepts with analogies?
Yes, this is a signature SkillVeris feature. Study notes use the Learn Through Hobbies method, explaining technical concepts through analogies from twelve domains including cricket, music, gaming, photography, travel, movies, fitness, chess, cooking, finance, business and sports. You can switch the analogy domain instantly to whichever hobby makes the concept click.
Are the revision notes suitable for last-minute exam preparation?
Yes, revision notes on SkillVeris work well for last-minute preparation because every section states the answer in its first sentences, so skimming is genuinely effective. Pair them with the relevant cheat sheet for formulas and syntax, and use the glossary for any unfamiliar term you meet while cramming.
Is there free study material for AI and machine learning?
Yes, SkillVeris provides free study notes across its AI and ML catalogue, covering Python for AI, deep learning frameworks like PyTorch and TensorFlow, Hugging Face Transformers, Large Language Models, RAG, AI agents and MLOps. All of it is free, making it a strong resource for Indian students and global learners alike.
Can beginners understand the study notes, or are they for experts?
Beginners can absolutely use them. The notes are written in plain language, define terms as they appear, and lean on hobby analogies to make abstract ideas concrete. Difficulty scales with the underlying course level, so beginner-course notes stay gentle while advanced-course notes go deeper, and the glossary supports you throughout.
How do study notes connect with SkillVeris courses?
Study notes are organised by course and topic, so they map directly to the structured courses and their 24–40-lesson curriculum. Many learners study a lesson first, then use the matching notes for revision before module assessments and the final exam, where 80 percent is required to pass and earn the certificate.
Are there study notes for Python specifically?
Yes, Python is well covered through notes tied to the Python-focused courses, including Python for AI and ML. Topics span fundamentals through applied machine learning usage. You can reinforce the notes with Python practice in Code Lab, which runs code in your browser with no installation required.
Do the study notes include code examples?
Yes, study notes include code examples wherever a concept is best shown in code, alongside explanations, key points and analogies. Reading a snippet in the notes and then reproducing it yourself in Code Lab is an effective loop, since Code Lab lets you run code in the browser across six languages.
How often is new study material added to SkillVeris?
Study material grows alongside the course catalogue. Whenever new courses join the platform's 37 live courses, matching study notes, glossary entries and cheat sheets are added so the resources stay in sync. Existing notes are also refined over time, so it is worth revisiting topics you studied earlier.
Can I use SkillVeris notes to prepare for technical interviews?
Yes, the notes make excellent interview revision because they compress each concept into direct, answer-first explanations, which mirrors how you should answer interview questions. Combine them with the SkillVeris interview questions feature, which includes readiness scoring, to test whether your revision has actually made you interview-ready.
Are the study notes mobile-friendly for studying on the go?
Yes, the study notes are built to load fast and read comfortably on mobile devices, so you can revise during a commute or between classes. Sections are short and answer-first, which suits small screens, and analogy switching works on mobile too, letting you study anywhere without carrying books.
What is the difference between study notes and cheat sheets?
Study notes explain concepts in depth with context, examples and analogies, making them ideal for learning and revision. Cheat sheets are compact quick-reference summaries of syntax, commands and key facts, ideal once you already understand a topic. Most learners study the notes first, then keep the cheat sheet handy while coding.
Do study notes help if I am stuck on a course lesson?
Yes, reading the matching study notes often clarifies a lesson because the same concept is explained from a different angle, frequently with a different analogy. If you are still stuck, ask the AI Mentor, which answers 24/7 at Quick, Detailed or Deep-dive depth until the idea genuinely makes sense.
Is there free study material for DevOps and cloud topics?
Yes, SkillVeris carries free study notes for DevOps and cloud topics as part of its coverage across 37 live courses. The material suits learners following the DevOps Engineer or Cloud Engineer paths, and it links to related glossary terms and cheat sheets so you can revise the whole toolchain in one place.
Can school or college students in India use these notes for projects?
Yes, students across India and worldwide use SkillVeris notes for coursework, projects and exam preparation, and everything is free, which matters for student budgets. The notes explain concepts clearly enough to cite in project reports, and Code Lab lets you prototype the project code directly in your browser.
How should I combine study notes with other SkillVeris resources?
A proven loop: learn from a course lesson, revise with the matching study notes, look up unfamiliar terms in the glossary, keep the cheat sheet open while practising in Code Lab, and quiz yourself with interview questions. The AI Mentor fills any remaining gaps 24/7, at whatever depth you need.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse