C Strings in C Programming
On this page (12sections)
Introduction
Unlike many modern languages, C has no built-in string type. A string is a character array terminated by a null character ('\0', ASCII 0). This is one of the most important concepts in C programming.
Declaring Strings
char name[20] = "Kumar"; /* 5 chars + '\0' */
char greeting[] = "Hello"; /* size inferred: 6 bytes */
char ch = 'A'; /* single character, not a string */
The compiler automatically adds '\0' at the end of string literals.
Reading and Printing Strings
#include <stdio.h>
int main(void) {
char name[50];
printf("Enter your name: ");
scanf("%49s", name);
printf("Hello, %s!\n", name);
return 0;
}
Use %s with printf. For safer input with spaces, use fgets(name, sizeof(name), stdin).
String Length with strlen
From <string.h>:
#include <stdio.h>
#include <string.h>
int main(void) {
char word[] = "Hello";
printf("Length: %zu\n", strlen(word));
return 0;
}
Sample Output
Length: 5
strlen counts characters before the null terminator — it does not include '\0'.
Common String Functions
| Function | Purpose | Example |
|---|---|---|
strlen(s) | Length of string | strlen("Hi") → 2 |
strcpy(dest, src) | Copy src to dest | strcpy(a, b) |
strcat(dest, src) | Append src to dest | strcat(a, b) |
strcmp(s1, s2) | Compare two strings | returns 0 if equal |
strncpy, strncat | Bounded versions (safer) | strncpy(dest, src, n) |
Comparing Strings
Never use == to compare string contents — that compares addresses. Use strcmp:
if (strcmp(name, "admin") == 0)
printf("Welcome, admin\n");
Manual String Traversal
char str[] = "C language";
int i = 0;
while (str[i] != '\0') {
printf("%c", str[i]);
i++;
}
Best Practices
- Always leave room for
'\0'— a 10-char string needschar s[11]. - Use
strncpy/strncatorsnprintfwhen buffer size is limited. - Prefer
const char*for read-only string parameters. - Initialize char arrays or set first byte to
'\0'before strcat.
Common Mistakes
- Buffer overflow — writing past array bounds with
strcpy. - Forgetting null terminator when building strings manually.
- Comparing strings with
==instead ofstrcmp. - Using
%sin scanf without width limit.
Related Programs
Explore our String Example Programs including strlen, strrev, strcpy and concatenation examples.
Frequently Asked Questions
How are strings stored in C?
C strings are char arrays ending with a null character '\0'. The null marks the end — there is no separate length field.
Why does strcpy need a large enough destination buffer?
strcpy copies until it finds '\0' with no bounds checking. If the destination is too small, it overflows the buffer.