C Strings
Treat text as a character array that ends at \0, keep capacity visible, and never use gets().
A C string is a character array terminated by \0
C has no built-in string object. char city[16] = "Rabat"; creates a writable array. The visible letters occupy positions 0 through 4; C places a terminating null character \0 at position 5. String-aware functions use that marker to know where text ends.
Capacity must include both the visible characters and the terminator. char city[6] = "Rabat"; fits exactly. char city[5] = "Rabat"; does not leave room for \0 and is invalid. Array indexes and index < count loops are the same rules as C Arrays; the extra rule is the terminator.
Print a full string and one selected character
%s prints until \\0. city[0] selects one character for %c.
Edit the program, predict its output, then run it.
Read text with a capacity-aware policy
gets() is removed from modern C and was never safe: it writes until a newline with no limit. Do not use it. scanf("%s", city) is also unsafe for a fixed buffer because it has no width. For a char city[16] that reads one whitespace-delimited word, use scanf("%15s", city);. The width leaves one slot for \0. It stops at whitespace, so it is not suitable for a name with spaces.
For a line of text, prefer fgets(city, sizeof city, stdin). It receives the buffer and its capacity, and it can retain spaces. Check the return value. It may keep a trailing newline when there is room; real programs often remove that newline before comparison or display.
string.h counts and compares characters, not capacity
\0.#include <string.h>It does not know the array's total capacity. Only use it with a properly terminated string.strcmp(a, b) == 0 for equal text.if (strcmp(city, "Rabat") == 0) { ... }== on arrays compares addresses, not characters.\0.char copy[16];Prefer a bounded copy such as snprintf(copy, sizeof copy, "%s", city) when the source length is not proven.#include <stdio.h>
#include <string.h>
int main(void) {
char city[16] = "Rabat";
printf("Length: %zu\n", strlen(city));
if (strcmp(city, "Rabat") == 0) {
puts("Match");
}
return 0;
}Do not write through a pointer to a string literal
char city[] = "Rabat"; creates an array you can modify. char *city = "Rabat"; points at a string literal. Treat that literal as read-only: city[0] = 'r'; has undefined behavior. Use a character array whenever the program must change the characters. Pointer details continue in C Pointers.
Independent lab: a labeled report name
Store a report title in a char array large enough for the text plus \0, print it with %s, and print the first character with %c. Compile locally to add strlen and a strcmp check. Do not call gets().
Lesson review
- A C string is a
chararray that ends at\0. - Capacity must include the terminator.
%sprints the whole terminated string;%cprints one character.strlenandstrcmpneed a terminator; they do not know the buffer size.- Never use
gets(). Boundscanfor preferfgets.