PadhaikoAll subjects

Array and Pointer

Computer Programming (ENCT 101)

Open in the Padhaiko app

6.1 Introduction to an array

An array is a derived data type that stores a fixed-size, homogeneous collection of elements (all sharing the same data type) in contiguous (adjacent) memory locations under a single variable name. Individual elements are accessed in constant time O(1) using a zero-based integer index (subscript) from 0 to size - 1.

Key Characteristics of Arrays in C:


6.2 One-dimensional array

A one-dimensional (1D) array represents a linear list of elements addressed by a single subscript.


6.3 Two-dimensional array

A two-dimensional (2D) array represents a table or matrix organized in rows and columns, indexed by two subscripts: matrix[row][col].


6.4 Multidimensional array

C allows arrays with three or more dimensions, such as int cube[2][3][4]; (2 layers, 3 rows per layer, 4 columns per row, totaling 2 * 3 * 4 = 24 elements).

Multidimensional arrays generalize row-major layout: the rightmost subscript varies fastest in memory. When passing a multidimensional array to a function, all dimensions except the leftmost (first) must be specified so the compiler can compute element offsets (void process(int a[][3][4], int layers);).


6.5 Introduction to string

In C, there is no separate primitive string keyword. A string is a one-dimensional char array terminated by the special null character '\0' (ASCII value 0).

Definition

Null-Terminated C String

A C string of length L characters requires at least L + 1 bytes of storage: L bytes for the characters plus 1 byte for the terminating '\0' sentinel that marks the end of the string for functions like printf("%s"), strlen(), and strcpy().

Ways to Declare and Initialize Strings:

  1. String literal (automatically appends '\0'): char city[] = "Kathmandu"; (occupies 10 bytes: 9 letters + '\0').
  2. Character list (must include '\0' manually): char code[] = {'I', 'O', 'E', '\0'};
  3. Fixed-buffer declaration: char name[30] = "Arya"; (first 5 bytes hold 'A','r','y','a','\0'; remaining 25 bytes are 0).

6.6 String handling functions

The standard header <string.h> provides functions to inspect, copy, concatenate, and compare null-terminated strings.

Standard String Functions in
FunctionPurposeReturn Value & Key Rule
strlen(s)Counts characters in s before '\0'Returns size_t length (excludes '\0')
strcpy(dest, src)Copies src (including '\0') into destReturns dest; dest must be large enough
strncpy(dest, src, n)Copies at most n characters from srcSafer, but manually set dest[n - 1] = '\0' if src is longer
strcat(dest, src)Appends src onto the end of dest (overwriting dest's '\0')Returns dest; dest must hold both strings + '\0'
strcmp(s1, s2)Lexicographically compares s1 and s2 by ASCII valuesReturns 0 if equal, < 0 if s1 < s2, > 0 if s1 > s2
strrev(s) (non-standard)Reverses string in place (Turbo C / older MSVC only)Not part of ANSI C; write a two-pointer swap loop in standard C

6.7 Definition of a pointer

Definition

Pointer Variable

A pointer is a variable whose value is the memory address of another variable or memory block rather than a direct data value.

Two fundamental unary operators power pointers in C:

Why Pointers Are Essential:

  1. Call by Reference: Enables functions to modify caller variables directly.
  2. Efficient Array and String Traversal: Avoids copying large buffers.
  3. Dynamic Memory Allocation: Manages heap blocks returned by malloc(), calloc(), and realloc().
  4. Data Structures: Builds linked lists, trees, and graphs.

6.8 Pointer declaration

A pointer declaration tells the compiler what type of data the pointer points to, which controls how many bytes are read/written on dereference (*p) and the step size of pointer arithmetic.

Syntax: data_type *pointer_name;

Pointer Declaration, Initialization, and DereferencingC
#include <stdio.h>

int main(void) {
    int x = 25;
    int *p = &x;        /* p holds address of int x */

    printf("x = %d\n", x);
    printf("*p = %d\n", *p);

    *p = 99;            /* modifies x indirectly via p */
    printf("new x = %d\n", x);
    return 0;
}

Special Pointers:


6.9 Pointer arithmetic

Pointer arithmetic scales automatically by the size of the pointed-to type (sizeof(*ptr)), not by raw single bytes!

Valid and Invalid Pointer Arithmetic Operations (Assume int is 4 bytes, base p = 1000)
OperationMeaningResult Address (int *p = 1000)Valid?
p + k or p - kAdvances or retreats p by k elements (k * sizeof(*p) bytes)p + 3 -> 1000 + 3 * 4 = 1012Yes
p++ / p--Moves p to next or previous elementp++ -> 1004Yes
q - p (same array)Number of elements between two pointers of same type(1012 - 1000) / 4 = 3 elementsYes
p == q, p < qCompares memory positions within same array or NULL1 or 0Yes
p + q, p * 2, p / 2Adding, multiplying, or dividing addressesMeaningful address does not existIllegal (compile error)

6.10 Relationship between pointer and arrays

In C, arrays and pointers are tightly linked through array-to-pointer decay: in most expressions, an array's name automatically converts to a constant pointer to its first element (arr is equivalent to &arr[0]).

AspectArray Name (int arr[5])Pointer Variable (int *ptr)
ModifiabilityConstant address; arr++ or arr = ptr is illegalModifiable lvalue; ptr++ and ptr = arr are valid
sizeof Resultsizeof(arr) returns total array bytes (5 * 4 = 20)sizeof(ptr) returns pointer variable size (4 or 8 bytes)
Element Accessarr[i] is compiled identically as *(arr + i)ptr[i] is compiled identically as *(ptr + i)

Key Pointer–Array Equivalences:


Worked Examples

Example 1

1 (6 marks)

Suppose a 1D array int a[6] begins at base address 2000, and a 2D array int b[3][4] also begins at base address 2000 on a system where sizeof(int) = 4 bytes. Compute the exact byte address of:

  1. a[3]
  2. b[2][3] (using row-major storage).

1. Computing Address of 1D Element a[3]: Using Address(a[i]) = Base + i * W with Base = 2000, i = 3, W = 4: Address(a[3]) = 2000 + 3 * 4 = 2000 + 12 = 2012.

2. Computing Address of 2D Element b[2][3]: Using Address(b[i][j]) = Base + (i * C + j) * W with Base = 2000, i = 2, C = 4, j = 3, W = 4: Address(b[2][3]) = 2000 + (2 * 4 + 3) * 4 = 2000 + 11 * 4 = 2000 + 44 = 2044.

Answer:
  • Address(a[3]) = 2012
  • Address(b[2][3]) = 2044
Example 2

2 (6 marks)

Trace the output of the following C program that uses pointers and pointer arithmetic to traverse and modify an integer array:

Pointer Arithmetic and Array Equivalence TraceC
#include <stdio.h>

int main(void) {
    int nums[5] = {10, 20, 30, 40, 50};
    int *p = nums;
    int *q = &nums[3];

    printf("diff=%td\n", q - p);
    *p += *(p + 3);
    p += 2;
    printf("p0=%d p2=%d *q=%d\n", nums[0], *p, *q);
    return 0;
}

Tracing Initial Pointer Positions and q - p:

  • p points to nums[0] (10).
  • q points to nums[3] (40).
  • Pointer subtraction q - p returns the element distance (not bytes): 3 - 0 = 3. So the first line prints diff=3.

Tracing Dereferences and Updates:

  • *p += *(p + 3); modifies nums[0]: nums[0] = nums[0] + nums[3] = 10 + 40 = 50.
  • p += 2; advances p by 2 int elements from nums[0] to nums[2] (30).
  • Now nums[0] is 50, *p is nums[2] (30), and *q is nums[3] (40).
Answer:

Output:

Program OutputText
diff=3
p0=50 p2=30 *q=40
Example 3

3 (5 marks)

Write a C program to compute the length of a string and check whether it is a palindrome without using <string.h> functions (strlen or strrev), using pointers or array indexing. Trace it for "madam".

Two-Index / Two-Pointer Palindrome Method:

  1. Find string length len by counting characters until s[len] == '\0'.
  2. Initialize left = 0 and right = len - 1.
  3. While left < right: if s[left] != s[right], mark is_pal = 0 and break; otherwise advance left++ and right--.
Manual Palindrome Check Without <string.h>C
#include <stdio.h>

int main(void) {
    char s[] = "madam";
    int len = 0;
    while (s[len] != '\0') {
        len++;
    }

    int left = 0, right = len - 1, is_pal = 1;
    while (left < right) {
        if (s[left] != s[right]) {
            is_pal = 0;
            break;
        }
        left++;
        right--;
    }
    printf("len=%d palindrome=%d\n", len, is_pal);
    return 0;
}

Trace for "madam":

  • Length loop stops at index 5 ('\0'), so len = 5.
  • left = 0 ('m'), right = 4 ('m') -> match!
  • left = 1 ('a'), right = 3 ('a') -> match!
  • left = 2, right = 2 -> left < right is false; loop ends with is_pal = 1.
Answer:

Output: len=5 palindrome=1 ("madam" is a palindrome of length 5).


Exercises

Exercises — Array and Pointer

Question 1

A 2D array double grid[4][5] starts at base memory address 5000 (with sizeof(double) = 8 bytes). Calculate the byte address of grid[1][3] assuming C's row-major storage.

Applying the Row-Major Address Formula: For grid[R][C] with R = 4, C = 5, Base = 5000, W = 8, and target indices i = 1, j = 3: Address(grid[1][3]) = Base + (i * C + j) * W = 5000 + (1 * 5 + 3) * 8 = 5000 + 8 * 8 = 5000 + 64 = 5064.

Answer:

Address(grid[1][3]) = 5064.

Question 2

Explain four standard <string.h> functions (strlen(), strcpy(), strcat(), strcmp()) and predict the output of: char a[20] = "Institute of Engineering"; char b[] = "TU"; strcat(a, b); printf("%s %zu %d\n", a, strlen(a), strcmp("abc", "abd"));

Function Roles:

  • strlen(s): returns character count before '\0'.
  • strcpy(d, s): copies s into d.
  • strcat(d, s): appends s to the end of d.
  • strcmp(s1, s2): compares ASCII codes (0 if equal, negative if s1 < s2, positive if s1 > s2).

Tracing the Snippet:

  • strcat(a, b) changes a from "Institute of Engineering" to "IOETU".
  • strlen("IOETU") is 5.
  • strcmp("abc", "abd") compares 'c' (99) vs 'd' (100), returning a negative integer (typically -1, i.e., < 0).
Answer:

Output: IOETU 5 followed by a negative integer (< 0, typically -1 from 99 - 100).

Question 3

Differentiate between an array name and a pointer variable in C (at least three points). Write a short C loop using pointer notation *(arr + i) to compute the sum of a 5-element integer array.

Array Name vs. Pointer Variable:

  1. Reassignment: An array name is a non-modifiable constant address (arr++ is invalid), whereas a pointer variable can be reassigned and incremented (ptr++ is valid).
  2. sizeof Behavior: sizeof(arr) returns the total bytes of the entire array (N * sizeof(type)), whereas sizeof(ptr) returns only the pointer's own address size (4 or 8 bytes).
  3. Storage: Declaring int arr[5]; allocates space for 5 integers; declaring int *ptr; allocates space only for one address.

Pointer-Notation Sum Loop:

Array Sum via Pointer DereferenceC
int arr[5] = {10, 20, 30, 40, 50}, sum = 0;
for (int i = 0; i < 5; i++) {
    sum += *(arr + i);
}

For {10, 20, 30, 40, 50}, sum becomes 150.

Answer:

Array names are fixed addresses whose sizeof equals total buffer size, whereas pointer variables can be reassigned (ptr++) and have fixed address size. Using sum += *(arr + i); traverses elements via pointer arithmetic (150 for {10, 20, 30, 40, 50}).

Question 4

Why are p + q and p * 2 illegal in C pointer arithmetic, whereas p + 2 and q - p are legal? If double *p is at address 3000 (sizeof(double) = 8) and int *a is at 3000, int *b is at 3020 (sizeof(int) = 4), find p + 2 and b - a.

Meaningfulness of Pointer Operations: Adding or multiplying two memory addresses (p + q, p * 2) produces a meaningless address outside allocated objects. By contrast, adding an integer offset (p + k) steps k elements forward in an array, and subtracting two pointers within the same array (b - a) computes the number of elements separating them.

Numeric Evaluation:

  • For double *p = 3000 (sizeof(double) = 8): p + 2 advances 2 * 8 = 16 bytes -> address 3000 + 16 = 3016.
  • For int *a = 3000, int *b = 3020 (sizeof(int) = 4): b - a = (3020 - 3000) / 4 = 20 / 4 = 5 elements.
Answer:

p + q and p * 2 yield invalid addresses and are forbidden, while p + 2 steps by 2 * sizeof(*p) and b - a counts elements between pointers. Here, p + 2 (for double *) = 3016, and b - a (for int *) = 5 elements.

Question 5

What is a NULL pointer and how does it differ from an uninitialized (wild) pointer and a void * generic pointer?

Comparing the Three Pointer Concepts:

  1. NULL Pointer: Explicitly assigned the null pointer constant (NULL), guaranteeing it points to no valid object and can be safely tested with if (p != NULL).
  2. Uninitialized (Wild) Pointer: A local pointer declared without initialization (int *p;) holding an arbitrary garbage address; dereferencing it causes crashes or silent memory corruption.
  3. void * (Generic Pointer): A pointer holding a valid address without an associated data type; it can receive any object pointer without a cast, but must be cast back to a specific pointer type (e.g., (int *)vp) before dereferencing.
Answer:

NULL explicitly marks "points to nothing" for safe checking, a wild pointer holds uninitialized garbage and is dangerous to dereference, and void * is a typeless generic address holder that must be cast to a typed pointer before dereferencing.

← Control StructuresUser-defined Functions →