Pointers with arrays and strings
Pointers with arrays and strings: array–pointer relation, pointer arithmetic, strings as char arrays, passing arrays to functions (1D and 2D), and safe string handling.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Pointers with arrays and strings are everywhere in C: processing sensor data (arrays) efficiently, parsing network packets or file contents (byte arrays), and manipulating messages or filenames (strings). Understanding how arrays “decay” to pointers and how strings are represented in memory lets you write safe, fast, and correct embedded, systems, and application code.
Key ideas
- Pointer: A variable that stores a memory address of a specific type. Example:
int *p;can store the address of anint. - Pointer arithmetic: For a pointer
pof typeT *,p + kmoves forward bykelements (address changes byk * sizeof(T)).p1 - p2is valid only when both point into the same array (or one-past-the-end), giving element difference of typeptrdiff_t. - One-past-the-end rule: A pointer may point to the element just past the last element of an array (e.g.,
a + n), but you must not dereference it. - Difference between
aand&a: Forint a[10];:ain expressions decays toint *(points toa[0]).&ais of typeint (*)[10](pointer to the entire array). Both have the same numeric address but different types and different behavior under arithmetic.
- String: In C, a string is a sequence of characters terminated by a null character
\0stored in achararray. Example:char s[] = "Hi";stores{'H','i','\0'}. - String literal: A string constant like
"Hello". In C, a string literal has type "array ofchar" with static storage duration; attempting to modify it has undefined behavior. Many compilers place literals in read-only memory; therefore preferconst char *p = "Hello";if you will not modify the data. char[]vschar *for strings:char name[] = "abc";allocates array in the current scope and copies characters including\0.char *p = "abc";points to a string literal; do not modify throughp.
strlenvssizeof:strlen(s)counts characters before\0, not including it; requires a proper null terminator and runs at runtime.sizeof s(whensis an array in scope) gives total bytes of the array; it's a compile-time constant for arrays with fixed size, but for variable length arrays (VLAs) it is evaluated at runtime. In function parameters,char s[]is identical tochar *s;sizeof sthere yields the size of a pointer.
- Passing arrays to functions: Arrays decay to pointers; functions receive a pointer and need an additional size parameter. Example:
void f(int *a, size_t n); - Multidimensional arrays: Stored in row-major order (rows one after another). For
int m[R][C];element accessm[i][j]equals*(*(m + i) + j). When passing to a function, all dimensions except the first must be specified:void g(int m[][C], size_t R);or use a pointer to array:void g(int (*p)[C], size_t R); - Const correctness with pointers:
const char *p: pointer to const char (cannot modify the char viap).char *const p: const pointer to char (pointer value cannot change; char may be modified).const char *const p: const pointer to const char.
- Memory safety with strings:
scanf("%s", buf)stops at whitespace and can overflow if width not limited. Use width:scanf("%19s", buf);forchar buf[20];or preferfgets.fgetsreads up ton-1chars and appends\0; it keeps the trailing newline if space permits.strcpyassumes destination is large enough;strncpymay not null-terminate if truncated. A common safe pattern: ensure space, usesnprintforstrncatcarefully, and always force a\0at the end.
Diagram to draw (when asked):
- Title: "Array and pointer views"
- Draw a row of boxes labeled
a[0],a[1], … with addresses under each. - An arrow labeled
aand&a[0]pointing to the first box. - A separate arrow labeled
&apointing to the left bracket enclosing the entire row, with a note: typeint (*)[N]. - For strings, draw
s[0]='H',s[1]='i',s[2]='\0'and annotate thatstrlen(s)=2.
Formulas
*(p + k)— Access the elementkpositions ahead.a[i] == *(a + i)and&a[i] == a + i— Array indexing equivalences.m[i][j] == *(*(m + i) + j)— 2D array indexing equivalence.void f(int a[], size_t n)— Function parametera[]is same asint *a.void g(int m[][C], size_t R)— For 2D arrays, all but the first dimension must be specified.int (*p)[C] = m;— Pointer to an array ofCints (points to each row).strlen(s)— Returns number of chars before\0(typesize_t).sizeof s— For arrays with fixed size in scope, total bytes (a compile-time constant); for variable length arrays it’s evaluated at runtime; for pointers, size of pointer type.fgets(buf, sizeof buf, stdin)— Safe input into a char array, keeps newline if space.scanf("%Ns", buf)— Limit%sto at mostNchars plus\0inbufof sizeN+1.const char *p— Pointer to read-only characters (do not modify throughp).
Worked examples
Example 1: Sum and average of an int array using pointer arithmetic Program:
#include <stdio.h>
int main(void) {
int a[] = {5, -2, 7, 0, 12};
size_t n = sizeof a / sizeof a[0];
int *p = a; // points to a[0]
long sum = 0; // use wider type to reduce overflow risk for larger arrays
printf("Array elements: ");
for (size_t i = 0; i < n; i++) {
// Using pointer arithmetic rather than indexing
printf("%d%s", *(p + i), (i + 1 == n) ? "\n" : " ");
sum += *(p + i);
}
double avg = (n > 0) ? (double)sum / (double)n : 0.0;
printf("Sum = %ld\n", sum);
printf("Average = %.1f\n", avg);
return 0;
}
Sample input:
- (no input) Sample output:
Array elements: 5 -2 7 0 12
Sum = 22
Average = 4.4
Example 2: Strings — read a line safely, measure length, and count vowels using a pointer Program:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
size_t count_vowels(const char *s) {
size_t c = 0;
for (const char *p = s; *p != '\0'; ++p) {
char ch = (char)tolower((unsigned char)*p);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
c++;
}
}
return c;
}
int main(void) {
char buf[100];
printf("Enter a line: ");
if (fgets(buf, sizeof buf, stdin) == NULL) {
return 0; // no input
}
// Remove trailing newline if present
size_t len = strlen(buf);
if (len > 0 && buf[len - 1] == '\n') {
buf[len - 1] = '\0';
len--;
}
size_t vowels = count_vowels(buf);
printf("Input: %s\n", buf);
printf("Length (strlen) = %zu\n", len);
printf("Buffer capacity (sizeof) = %zu\n", sizeof buf);
printf("Vowel count = %zu\n", vowels);
return 0;
}
Sample input:
Hello World
Sample output:
Enter a line: Input: Hello World
Length (strlen) = 11
Buffer capacity (sizeof) = 100
Vowel count = 3
Example 3: 2D arrays — pass to functions and use pointer-to-array Program:
#include <stdio.h>
void print_matrix_rows(int a[][3], size_t rows) { // 3 columns fixed
for (size_t i = 0; i < rows; ++i) {
for (size_t j = 0; j < 3; ++j) {
printf("%d%s", a[i][j], (j + 1 == 3) ? "\n" : " ");
}
}
}
int sum_using_ptr_to_row(int (*p)[3], size_t rows) {
int sum = 0;
for (size_t i = 0; i < rows; ++i) {
// p points to each row, which is an array of 3 ints
for (size_t j = 0; j < 3; ++j) {
sum += *(*(p + i) + j); // same as p[i][j]
}
}
return sum;
}
int main(void) {
int m[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
printf("Matrix:\n");
print_matrix_rows(m, 2);
int (*rowp)[3] = m; // pointer to an array of 3 ints (points to row 0)
int sum = sum_using_ptr_to_row(rowp, 2);
// Demonstrate equivalent indexing
int val = *(*(m + 1) + 2); // m[1][2] == 6
printf("Sum = %d\n", sum);
printf("m[1][2] via pointer arithmetic = %d\n", val);
return 0;
}
Sample input:
- (no input) Sample output:
Matrix:
1 2 3
4 5 6
Sum = 21
m[1][2] via pointer arithmetic = 6
Common mistakes
- Forgetting space for the null terminator:
char s[3] = "abc";overflows because 4 bytes are needed ('a','b','c',\0). - Using
scanf("%s", buf)without a field width, causing buffer overflow. Always bound it: forchar buf[20];usescanf("%19s", buf);or preferfgets. - Misunderstanding
strncpy: it does not guarantee a\0if the source is longer than the limit. Manually ensure termination. - Confusing
aand&a: incrementingint *p = a; p++moves by oneint; incrementingint (*q)[10] = &a; q++moves by 10ints (to the next whole array — typically only meaningful with arrays of arrays). - Dereferencing one-past-the-end:
*(a + n)is invalid; onlya + nas a sentinel is valid. - For 2D arrays, trying to write
void f(int **m)to acceptint m[R][C]. This is incompatible; usevoid f(int m[][C])orvoid f(int (*m)[C])with knownC. - Forgetting that
fgetskeeps the newline if there is room; results in unexpected\nin the string when printing or comparing. Trim it if needed.
For your exam
- Diagrams: labeled memory layout of an array and a string; show
a,&a,&a[0]arrows with types annotated. - Programs:
- Traverse an array using pointers to compute sum/average/min/max.
- Read a line safely and operate on it (count vowels, words, reverse string) using pointer traversal.
- Pass a 2D array to a function and print or sum elements; demonstrate
*(*(m+i)+j).
- What full-marks answers include: correct declarations and types, explanation of decay exceptions (
sizeof,&), correct pointer arithmetic (units aresizeof(type)), correct handling of\0, safe input/output, and clean, compiling C code with sample I/O. Include complexity/space notes if asked, and mention undefined behavior cases clearly.
Quick check
- State the relationship between
a[i]and pointer notation. - Why must all but the first dimension be specified when passing a 2D array to a function?
- For
char s[] = "Exam";what arestrlen(s)andsizeof s?
Answers: 1) a[i] == *(a + i) and &a[i] == a + i. 2) The compiler must know the column size to compute row offsets in row-major order; thus later dimensions are required. 3) strlen(s) = 4, sizeof s = 5 bytes (includes the \0).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?