Arrays & Strings
In C, arrays are fixed-size contiguous memory blocks and strings are null-terminated char arrays. Understanding arrays and strings is essential — many security vulnerabilities come from incorrect buffer handling.
40 min•By Priygop Team•Last updated: Feb 2026
Arrays & Strings Code
Example
#include <stdio.h>
#include <string.h>
int main() {
// Array declaration and initialization
int numbers[5] = {10, 20, 30, 40, 50};
int zeros[100] = {0}; // All elements initialized to 0
// Array access
printf("First: %d, Last: %d\n", numbers[0], numbers[4]);
// No bounds checking! numbers[10] compiles but crashes/corrupts
// Array iteration
int size = sizeof(numbers) / sizeof(numbers[0]); // 5
for (int i = 0; i < size; i++) {
printf("%d ", numbers[i]);
}
// 2D array
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Strings (null-terminated char arrays)
char greeting[] = "Hello"; // Auto-sized: 6 chars (5 + null \0)
char name[50]; // Buffer for up to 49 chars + null
// String functions (string.h)
printf("Length: %zu\n", strlen(greeting)); // 5
strcpy(name, "Alice"); // Copy
strcat(name, " Smith"); // Concatenate
printf("Name: %s\n", name); // "Alice Smith"
// Safe alternatives (prevent buffer overflow)
strncpy(name, "Bob", sizeof(name) - 1);
name[sizeof(name) - 1] = '\0'; // Ensure null termination
// String comparison
if (strcmp(greeting, "Hello") == 0) {
printf("Strings are equal\n");
}
// strcmp returns: 0 (equal), <0 (first < second), >0 (first > second)
// Character operations
char ch = 'A';
printf("Lowercase: %c\n", ch + 32); // 'a' (ASCII math)
return 0;
}