← Back to C Course | Chapter 6: Arrays & Strings | Lesson 6 of 8

C Strings

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?

c
#include <stdio.h>
int main() {
	char name[] = "Hi";
	printf("%s", name);
	return 0;
}

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

c
#include <stdio.h>
int main() {
	char name[20] = "Alex";
	printf("%s", name);
	return 0;
}

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

c
#include <stdio.h>
int main() {
	char str[] = "Hi";
	int i = 0;
	while (str[i] != '\0') {
		i++;
	}
	printf("%d", i);
	return 0;
}

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

c
#include <stdio.h>
int main() {
	char name[] = "Jill";
	name[0] = 'J';
	printf("%s", name);
	return 0;
}

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

c
#include <stdio.h>
int main() {
	char buffer[20] = "Sample\n";
	printf("%s", buffer);
	return 0;
}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.