Lesson 5 of 12
Arrays & Strings
Learn how C stores and . A C string is just an array of characters ending in a (\0), and knowing that helps you avoid common .
#include <stdio.h>
#include <string.h>
int main() {
// Arrays — fixed size, all same type
int numbers[5] = {10, 20, 30, 40, 50};
printf("%d\n", numbers[0]); // 10
printf("%d\n", numbers[4]); // 50
// Partial initialization — rest is zero
int data[10] = {1, 2, 3}; // data[3..9] = 0
// Iterate
int len = sizeof(numbers) / sizeof(numbers[0]); // common idiom
for (int i = 0; i < len; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
// 2D arrays
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
printf("Center: %d\n", matrix[1][1]); // 5
// Strings — char arrays ending with '\0'
char greeting[] = "Hello"; // compiler adds '\0'
char name[50] = "World"; // 50-byte buffer
printf("%s\n", greeting); // Hello
printf("Length: %zu\n", strlen(greeting)); // 5 (not counting '\0')
// String functions from <string.h>
char full[100];
strcpy(full, greeting); // copy greeting into full
strcat(full, ", "); // append
strcat(full, name); // append
strcat(full, "!");
printf("%s\n", full); // Hello, World!
printf("%d\n", strcmp("abc", "abc")); // 0 — strings are equal
printf("%d\n", strcmp("abc", "xyz")); // negative — abc < xyz
return 0;
}Finished reading?Mark it done to track your progress.
Tip: use the ← and → keys to move between lessons.