C Strings
1. What is a String in C?
-
In C, a string is an array of characters terminated by a null character
\0. -
The null character
\0marks the end of the string.
Example of a string:
Here, the memory contains:
Alice\0.
2. Declaring Strings
1D Character Array
Pointer to String
Using a pointer is simpler but cannot modify string literal.
3. Input and Output Strings
Printing Strings
Output:
-
Use
%sformat specifier inprintfto print strings.
Reading Strings
Input/Output:
Note:
scanf("%s")cannot read strings with spaces.
Reading Strings with Spaces Using fgets
Input/Output:
4. Common String Functions (<string.h>)
| Function | Description |
|---|---|
strlen(str) |
Returns length of string (without \0) |
strcpy(dest, src) |
Copies src into dest |
strcat(dest, src) |
Appends src to the end of dest |
strcmp(str1, str2) |
Compares two strings (0 if equal) |
strncpy(dest, src, n) |
Copies first n characters from src to dest |
strncat(dest, src, n) |
Appends first n characters of src to dest |
Example:
Output:
5. Key Points About Strings in C
-
Strings are character arrays ending with
\0. -
Use
%sfor printing andscanf/fgetsfor input. -
Include
<string.h>to use built-in string functions. -
Avoid exceeding array size → buffer overflow.
-
C strings are mutable if stored in a character array, but string literals via pointer cannot be modified safely.
6. Real-Life Example: Greeting Program
Sample Input/Output:
Real-life use: Reading user input, names, addresses, or text messages.
