What are Strings?
In C programming, a string is a sequence of characters. Strings are used to store and manipulate text.
Unlike some other programming languages, C doesn't have a built-in string data type. Instead, strings are implemented as arrays of characters.
String Declaration and Initialization
There are several ways to declare and initialize strings in C:
Method 1: Character Array with Size
char name[20]; // Declares a string that can hold up to 19 characters + null terminator
Method 2: Initialize with String Literal
char greeting[] = "Hello World"; // Size automatically determined
char message[50] = "Welcome to C programming"; // Explicit size with initialization
Method 3: Character by Character
char word[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Manual initialization
Note: In C, a string is a sequence of characters ending with a null character (\0)
The Null Terminator (\0)
The null terminator is crucial in C strings. It marks the end of the string and helps functions know where to stop processing characters.
char example[] = "Cat";
// Memory layout: ['C']['a']['t']['\0']
// Positions: [0] [1] [2] [3]
Basic String Operations
Reading Strings
#include <stdio.h>
int main() {
char name[50];
printf("Enter your name: ");
scanf("%s", name); // Note: no '&' needed for strings
printf("Hello, %s!\n", name);
return 0;
}
Displaying Strings
char city[] = "New York";
printf("City: %s\n", city); // %s is the format specifier for strings
Important Notes
| Aspect | Details |
|---|---|
| Size Limit | Always ensure your array is large enough to hold the string + null terminator |
| Input Limitation | scanf("%s", ...) stops at whitespace (space, tab, newline) |
| Memory | Strings occupy consecutive memory locations |
| Indexing | Access individual characters using array notation: string[0], string[1], etc. |
Common Beginner Mistakes
- Forgetting the null terminator when manually creating strings
- Array size too small - remember to account for
\0 - Using
&with scanf for strings - not needed since array name is already an address
Strings are fundamental in C programming and you'll use them frequently for handling text data. In the next topics, we'll explore string functions that make working with strings much easier!