First Year Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

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 an int.
  • Pointer arithmetic: For a pointer p of type T *, p + k moves forward by k elements (address changes by k * sizeof(T)). p1 - p2 is valid only when both point into the same array (or one-past-the-end), giving element difference of type ptrdiff_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 a and &a: For int a[10];:
    • a in expressions decays to int * (points to a[0]).
    • &a is of type int (*)[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 \0 stored in a char array. Example: char s[] = "Hi"; stores {'H','i','\0'}.
  • String literal: A string constant like "Hello". In C, a string literal has type "array of char" with static storage duration; attempting to modify it has undefined behavior. Many compilers place literals in read-only memory; therefore prefer const char *p = "Hello"; if you will not modify the data.
  • char[] vs char * 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 through p.
  • strlen vs sizeof:
    • strlen(s) counts characters before \0, not including it; requires a proper null terminator and runs at runtime.
    • sizeof s (when s is 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 to char *s; sizeof s there 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 access m[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 via p).
    • 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); for char buf[20]; or prefer fgets.
    • fgets reads up to n-1 chars and appends \0; it keeps the trailing newline if space permits.
    • strcpy assumes destination is large enough; strncpy may not null-terminate if truncated. A common safe pattern: ensure space, use snprintf or strncat carefully, and always force a \0 at 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 a and &a[0] pointing to the first box.
  • A separate arrow labeled &a pointing to the left bracket enclosing the entire row, with a note: type int (*)[N].
  • For strings, draw s[0]='H', s[1]='i', s[2]='\0' and annotate that strlen(s)=2.

Formulas

  • *(p + k) — Access the element k positions 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 parameter a[] is same as int *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 of C ints (points to each row).
  • strlen(s) — Returns number of chars before \0 (type size_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 %s to at most N chars plus \0 in buf of size N+1.
  • const char *p — Pointer to read-only characters (do not modify through p).

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: for char buf[20]; use scanf("%19s", buf); or prefer fgets.
  • Misunderstanding strncpy: it does not guarantee a \0 if the source is longer than the limit. Manually ensure termination.
  • Confusing a and &a: incrementing int *p = a; p++ moves by one int; incrementing int (*q)[10] = &a; q++ moves by 10 ints (to the next whole array — typically only meaningful with arrays of arrays).
  • Dereferencing one-past-the-end: *(a + n) is invalid; only a + n as a sentinel is valid.
  • For 2D arrays, trying to write void f(int **m) to accept int m[R][C]. This is incompatible; use void f(int m[][C]) or void f(int (*m)[C]) with known C.
  • Forgetting that fgets keeps the newline if there is room; results in unexpected \n in 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 are sizeof(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

  1. State the relationship between a[i] and pointer notation.
  2. Why must all but the first dimension be specified when passing a 2D array to a function?
  3. For char s[] = "Exam"; what are strlen(s) and sizeof 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?