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

C Array of Strings

Declaring an Array of Strings

A declaration like char names[5][20] reserves room for 5 strings of up to 19 visible characters each (plus the null terminator) -- it's rigid but simple, unlike an array of char pointers which lets each string have its own independently-sized buffer.

Example: Declaring an Array of Strings

c
#include <stdio.h>
int main() {
	char names[5][20];
	printf("%zu", sizeof(names));
	return 0;
}

Initializing String Arrays

Each string literal in the initializer list is automatically padded with unused bytes if it's shorter than the row width you declared, wasting a little memory but keeping every row the same fixed size for predictable indexing.

Example: Initializing String Arrays

c
#include <stdio.h>
int main() {
	char names[3][20] = {"Ann", "Bob", "Cat"};
	printf("%s", names[1]);
	return 0;
}

Accessing Strings inside the Array

names[2] gives you a pointer to the start of the third string in the array, which you can pass directly to functions like printf("%s", names[2]) or strlen(names[2]) exactly as you would any other string.

Example: Accessing Strings inside the Array

c
#include <stdio.h>
int main() {
	char names[3][20] = {"Ann", "Bob", "Cat"};
	printf("%s", names[2]);
	return 0;
}

Modifying Strings in the Array

Attempting names[2] = "NewValue" is a compile error for a fixed 2D char array because you cannot reassign an array row as if it were a pointer -- strcpy(names[2], "NewValue") is the correct way to replace a row's contents in place.

Example: Modifying Strings in the Array

c
#include <stdio.h>
#include <string.h>
int main() {
	char names[3][20] = {"Ann", "Bob", "Cat"};
	strcpy(names[2], "NewValue");
	printf("%s", names[2]);
	return 0;
}

Looping through String Arrays

A simple for loop from 0 to the row count lets you print or process each name; just be careful that whatever function you call inside the loop doesn't write more characters than the fixed row width can hold.

Example: Looping through String Arrays

c
#include <stdio.h>
int main() {
	char names[3][20] = {"Ann", "Bob", "Cat"};
	for (int i = 0; i < 3; i++) {
		printf("%s ", names[i]);
	}
	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.