Arrays and Strings
Arrays and Strings in C
1D arrays Fixed-size, contiguous sequences of elements:
c
int scores[5] = {90, 85, 78, 92, 88};Access with zero-based indexing: scores[0] through scores[4].
Multidimensional arrays
c
int grid[3][4]; // 3 rows, 4 columns
grid[1][2] = 5;Char arrays and strings
C strings are null-terminated char arrays ('\0' at the end):
c
char name[] = "Alice"; // 6 bytes: A,l,i,c,e,\0string.h functions
strlen(s)— length (excluding null terminator)strcpy(dst, src)— copystrcat(dst, src)— concatenatestrcmp(s1, s2)— compare (returns 0 if equal)strncpy,strncat,strncmp— safer bounded versions
Key points:
- Array names decay to pointers to the first element when passed to functions.
- Always ensure char arrays are large enough for the string plus the null terminator.
- Prefer
strncpyoverstrcpyto avoid buffer overflows.
Code Examples
1D array operationsc
#include <stdio.h>
int main(void) {
int scores[] = {72, 85, 90, 61, 78, 95};
int n = 6;
int sum = 0, max = scores[0];
for (int i = 0; i < n; i++) {
sum += scores[i];
if (scores[i] > max) max = scores[i];
}
printf("Average: %.1f\n", (double)sum / n);
printf("Maximum: %d\n", max);
// 2D array
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 3; c++) {
printf("%d ", matrix[r][c]);
}
printf("\n");
}
return 0;
}Arrays use zero-based indexing. 2D arrays are stored row-major in memory and accessed with two indices.
char arrays and string.hc
#include <stdio.h>
#include <string.h>
int main(void) {
char first[20] = "Hello";
char second[] = " World";
printf("Length of first: %zu\n", strlen(first));
strncat(first, second, sizeof(first) - strlen(first) - 1);
printf("Concatenated: %s\n", first);
char copy[20];
strncpy(copy, first, sizeof(copy) - 1);
copy[sizeof(copy) - 1] = '\0';
printf("Equal: %d\n", strcmp(first, copy) == 0);
printf("Upper comparison: %d\n", strcmp("abc", "ABC") > 0);
return 0;
}strncat and strncpy are safer bounded versions. strcmp returns 0 for equal strings, negative if s1 < s2, positive if s1 > s2.
Quick Quiz
1. What is the index of the first element of an array in C?
2. What marks the end of a C string?
Was this lesson helpful?