C Strings
In this page:
What is a String?
This null-terminator convention is what lets functions like strlen() know where a string ends without being told its length separately -- but it also means the underlying char array must always be at least one byte larger than the visible text to hold that trailing zero.
Example: What is a String?
#include <stdio.h>
int main() {
char name[] = "Hi";
printf("%s", name);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Declaring and Initializing
char name[20] reserves a fixed 20-byte buffer regardless of how much text you actually store in it, while char name[] = "Hi" lets the compiler size the array to exactly fit the initializer plus its null terminator (3 bytes here).
Example: Declaring and Initializing
#include <stdio.h>
int main() {
char name[20] = "Alex";
printf("%s", name);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
The Null-Terminator
Because \0 has the integer value 0, it's often described as falsy in conditional checks -- a common idiom like while (*str) loops until it hits the terminator, since any other character has a nonzero ASCII value.
Example: The Null-Terminator
#include <stdio.h>
int main() {
char str[] = "Hi";
int i = 0;
while (str[i] != '\0') {
i++;
}
printf("%d", i);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Accessing Characters
Since a C string is just a char array, name[0] = J changes only the first character; there's no dedicated string-replace function, and any modification that shortens the visible text still needs its own \0 placed at the new end.
Example: Accessing Characters
#include <stdio.h>
int main() {
char name[] = "Jill";
name[0] = 'J';
printf("%s", name);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Reading Strings safely with fgets
fgets() takes a maximum buffer size as an argument, so it can never write past the end of your array the way gets() can -- the one gotcha is that fgets() keeps the trailing newline character if there's room, which gets() never did.
Example: Reading Strings safely with fgets
#include <stdio.h>
int main() {
char buffer[20] = "Sample\n";
printf("%s", buffer);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: