Arrays and strings
An array is a fixed number of values of the same type, stored side by side in memory. A string in C is simply an array of characters that ends with a zero byte. Both are simple, fast, and the source of many of C's most famous bugs, so it's worth learning them carefully.
Arrays
#include <stdio.h>
int main(void) {
int scores[5] = {90, 72, 85, 64, 99};
scores[1] = 75; // change one element
int total = 0;
for (int i = 0; i < 5; i++) {
printf("scores[%d] = %d\n", i, scores[i]);
total += scores[i];
}
printf("total %d, average %.1f\n", total, total / 5.0);
return 0;
}scores[0] = 90 scores[1] = 75 scores[2] = 85 scores[3] = 64 scores[4] = 99 total 413, average 82.6
- Elements are numbered from 0, so a 5-element array goes from
scores[0]toscores[4]. - The size is fixed when the array is created.
int a[5] = {1, 2};sets the first two and fills the rest with 0;int a[5] = {0};zeroes everything. Leave out the size,int a[] = {1, 2, 3};, and the compiler counts for you.
How many elements?
#include <stdio.h>
#define COUNT(a) (sizeof(a) / sizeof((a)[0]))
int main(void) {
double prices[] = {9.99, 24.50, 3.75, 120.00};
printf("the array uses %zu bytes\n", sizeof prices);
printf("one element uses %zu bytes\n", sizeof prices[0]);
printf("so it has %zu elements\n", COUNT(prices));
return 0;
}the array uses 32 bytes one element uses 8 bytes so it has 4 elements
This sizeof trick only works where the array was declared. Passed to a function, an array becomes a pointer to its first element and loses its size, which is why functions take the length as a separate argument: void print_all(const double a[], size_t n).
No bounds checking
C does not check that an index is inside the array. Writing past the end silently overwrites whatever is next in memory:
#include <stdio.h>
int main(void) {
int a[3] = {1, 2, 3};
for (int i = 0; i <= 3; i++) { // bug: <= instead of <
printf("a[%d] = %d\n", i, a[i]);
}
return 0;
}gcc -std=c23 -Wall -Wextra -O2 -o main main.c
gcc -std=c23 -g -fsanitize=address -o main main.c && ./mainmain.c:6:9: warning: iteration 3 invokes undefined behavior [-Waggressive-loop-optimizations] main.c:5:23: note: within this loop --- with -fsanitize=address: ==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x... at pc 0x... bp READ of size 4 at 0x... thread T0
Off-by-one errors like this are the root of buffer overflows, historically the most exploited class of security bug. Two defences: the optimiser's warnings, and AddressSanitizer (-fsanitize=address), which stops the program at the exact bad access. Use it whenever you test. More in Debugging, sanitizers and safe C.
2D arrays
#include <stdio.h>
int main(void) {
int grid[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
};
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 4; c++) printf("%3d", grid[r][c]);
printf("\n");
}
printf("grid[2][1] = %d\n", grid[2][1]);
return 0;
}1 2 3 4 5 6 7 8 9 10 11 12 grid[2][1] = 10
The rows are stored one after another in memory ("row-major"), so looping over rows on the outside and columns inside is the fast way.
Strings
A string is a char array ending with the null character '\0' (a zero byte). That terminator is how functions know where the text ends:
#include <stdio.h>
#include <string.h>
int main(void) {
char name[] = "Asha";
printf("text: %s\n", name);
printf("strlen: %zu, sizeof: %zu\n", strlen(name), sizeof name);
for (size_t i = 0; i < sizeof name; i++) {
printf("name[%zu] = '%c' (%d)\n", i, name[i] ? name[i] : '0', name[i]);
}
return 0;
}text: Asha strlen: 4, sizeof: 5 name[0] = 'A' (65) name[1] = 's' (115) name[2] = 'h' (104) name[3] = 'a' (97) name[4] = '0' (0)
"Asha" takes 5 bytes: four letters and the terminator. strlen counts characters up to the '\0'; sizeof counts the bytes of the array. Always leave room for the terminator.
String literals vs arrays
#include <stdio.h>
int main(void) {
char editable[] = "hello"; // an array with a copy of the text: can change it
const char *fixed = "hello"; // points to read-only text: can't change it
editable[0] = 'J';
printf("%s %s\n", editable, fixed);
return 0;
}Jello hello
Writing fixed[0] = 'J' would crash (the text lives in read-only memory), which is why string literals should be pointed to with const char *.
The <string.h> functions
#include <stdio.h>
#include <string.h>
int main(void) {
char a[32] = "apple";
const char *b = "banana";
printf("strlen(a) = %zu\n", strlen(a));
printf("strcmp(a, b) = %d (negative: a sorts first)\n", strcmp(a, b) < 0 ? -1 : 1);
printf("strcmp(a, \"apple\") = %d (0: equal)\n", strcmp(a, "apple"));
printf("strchr(b, 'n') → \"%s\"\n", strchr(b, 'n'));
printf("strstr(\"pineapple\", \"apple\") → \"%s\"\n", strstr("pineapple", "apple"));
strcat(a, " pie"); // append (only safe because a has room)
printf("after strcat: %s\n", a);
return 0;
}strlen(a) = 5
strcmp(a, b) = -1 (negative: a sorts first)
strcmp(a, "apple") = 0 (0: equal)
strchr(b, 'n') → "nana"
strstr("pineapple", "apple") → "apple"
after strcat: apple pie| Function | Does |
|---|---|
strlen(s) |
Length, not counting '\0' |
strcmp(a, b) |
Compare: 0 if equal, negative/positive for sort order. Never compare strings with ==, which compares addresses |
strncmp(a, b, n) |
Compare the first n characters |
strchr(s, c) / strstr(s, sub) |
Find a character / substring; returns a pointer to it or NULL |
strcpy, strcat |
Copy / append, with no size check. Avoid them |
snprintf(buf, size, fmt, …) |
Build a string safely: never writes more than size bytes, always terminates |
Safe string building with snprintf
#include <stdio.h>
int main(void) {
char buf[16];
const char *user = "Asha";
int n = snprintf(buf, sizeof buf, "Hi %s, you have %d messages", user, 12);
printf("buffer: \"%s\"\n", buf);
printf("needed %d characters, buffer holds %zu\n", n, sizeof buf - 1);
if (n >= (int)sizeof buf) printf("→ truncated, but no overflow\n");
return 0;
}main.c: In function ‘main’:
main.c:6:54: warning: ‘, you have ’ directive output truncated writing 11 bytes into a region of size 9 [-Wformat-truncation=]
6 | int n = snprintf(buf, sizeof buf, "Hi %s, you have %d messages", user, 12);
| ~~~~~~~~~^~
main.c:6:13: note: ‘snprintf’ output 30 bytes into a destination of size 16
6 | int n = snprintf(buf, sizeof buf, "Hi %s, you have %d messages", user, 12);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
buffer: "Hi Asha, you ha"
needed 29 characters, buffer holds 15
→ truncated, but no overflowGCC even spotted the truncation at compile time. snprintf returns how long the full text would have been, so you can detect truncation. Use it instead of strcpy, strcat and sprintf whenever you write into a buffer.
Reading a line of input
scanf("%s") stops at the first space and doesn't know the buffer's size. Read whole lines with fgets instead:
#include <stdio.h>
#include <string.h>
int main(void) {
char name[32];
printf("Your full name: ");
if (fgets(name, sizeof name, stdin) == NULL) return 1;
name[strcspn(name, "\n")] = '\0'; // remove the newline fgets keeps
printf("Hello, %s! (%zu characters)\n", name, strlen(name));
return 0;
}./askYour full name: Asha Rao Hello, Asha Rao! (8 characters)
fgets(buf, size, stdin) reads at most size - 1 characters and always adds the terminator. strcspn finds the newline so it can be removed.
Turning text into numbers
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int parse_int(const char *text, long *out) {
char *end;
errno = 0;
long v = strtol(text, &end, 10);
if (end == text || *end != '\0' || errno == ERANGE) return -1;
*out = v;
return 0;
}
int main(void) {
const char *inputs[] = {"42", "-7", "12abc", "", "99999999999999999999"};
for (int i = 0; i < 5; i++) {
long v;
if (parse_int(inputs[i], &v) == 0) printf("\"%s\" → %ld\n", inputs[i], v);
else printf("\"%s\" → not a valid number\n", inputs[i]);
}
return 0;
}"42" → 42 "-7" → -7 "12abc" → not a valid number "" → not a valid number "99999999999999999999" → not a valid number
strtol tells you where it stopped (end) and whether the number was too big (errno == ERANGE), so you can reject bad input. atoi can't: it returns 0 for "abc" and for "0" alike. strtod does the same for decimals.
Processing characters
#include <stdio.h>
#include <ctype.h>
int main(void) {
char text[] = "Hello World, from C 23!";
int letters = 0, digits = 0, spaces = 0;
for (char *p = text; *p; p++) {
if (isalpha((unsigned char)*p)) letters++;
else if (isdigit((unsigned char)*p)) digits++;
else if (isspace((unsigned char)*p)) spaces++;
*p = (char)toupper((unsigned char)*p);
}
printf("%s\nletters %d, digits %d, spaces %d\n", text, letters, digits, spaces);
return 0;
}HELLO WORLD, FROM C 23! letters 15, digits 2, spaces 4
The loop walks the string until it reaches '\0' (which is false). The (unsigned char) casts are required by the <ctype.h> functions for characters outside plain ASCII.
Practice
- Write
void reverse(char *s)that reverses a string in place, and test it with"stressed". - Count the vowels in a line read with
fgets. - Write
int is_palindrome(const char *s)that ignores case. - Read a comma-separated line like
"Asha,31,Pune"and print each field on its own line (look upstrtok, or walk the string yourself).
1.How many bytes does char word[] = "code"; use?
2.How do you check whether two strings are equal?
3.What happens when you write to a[10] in a 10-element array?
4.Which function builds a string without risking a buffer overflow?