Array and Pointer
Open in the Padhaiko app6.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:
- Contiguous Storage: Element
arr[i]immediately followsarr[i - 1]in RAM with no gaps between elements. - Homogeneous Type: Every element has the exact same size (
sizeof(element_type)). - Zero-Based Indexing: The first element is always at index
0, and the last element of an array of sizeNis at indexN - 1. - Static Size (Standard Fixed Arrays): The size must be known when the array is allocated (constant expression in C89; variable-length arrays optional in C99/C11).
- No Automatic Bounds Checking: C does not check whether an index is within
0toN - 1; accessingarr[N]orarr[-1]causes undefined behavior.
6.2 One-dimensional array
A one-dimensional (1D) array represents a linear list of elements addressed by a single subscript.
- Declaration:
data_type array_name[size];Example:int marks[5];allocates5 * sizeof(int)bytes (typically20bytes). - Initialization:
- Full initialization:
int a[4] = {10, 20, 30, 40}; - Partial initialization:
int b[5] = {10, 20};(remaining elementsb[2],b[3],b[4]are automatically zero-initialized to0). - Unsized initialization:
int c[] = {5, 15, 25};(compiler deduces size3).
- Full initialization:
- Address Formula (1D): If the base address of
arrisBand each element occupiesWbytes (sizeof(arr[0])), the byte address ofarr[i]is:Address(arr[i]) = B + i * W
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].
- Declaration:
data_type name[rows][cols];Example:int mat[3][4];allocates3 * 4 = 12integers (48bytes for 4-byteint). - Initialization:
int a[2][3] = { {1, 2, 3}, {4, 5, 6} };When initializing a 2D array, the column size is mandatory even if row count is omitted:int b[][3] = { {1, 2, 3}, {4, 5, 6} };. - Row-Major Memory Layout in C: C stores 2D arrays in row-major order: all elements of row
0are stored contiguously first, followed by row1, then row2, and so on. Forint mat[R][C]with base addressBand element sizeW:Address(mat[i][j]) = B + (i * C + j) * W
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).
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:
- String literal (automatically appends
'\0'):char city[] = "Kathmandu";(occupies10bytes: 9 letters +'\0'). - Character list (must include
'\0'manually):char code[] = {'I', 'O', 'E', '\0'}; - Fixed-buffer declaration:
char name[30] = "Arya";(first 5 bytes hold'A','r','y','a','\0'; remaining 25 bytes are0).
6.6 String handling functions
The standard header <string.h> provides functions to inspect, copy, concatenate, and compare null-terminated strings.
| Function | Purpose | Return 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 dest | Returns dest; dest must be large enough |
strncpy(dest, src, n) | Copies at most n characters from src | Safer, 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 values | Returns 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
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:
- Address-of operator (
&):&xyields the starting memory address of variablex. - Indirection / Dereference operator (
*):*ptraccesses or modifies the value stored at the memory address held byptr.
Why Pointers Are Essential:
- Call by Reference: Enables functions to modify caller variables directly.
- Efficient Array and String Traversal: Avoids copying large buffers.
- Dynamic Memory Allocation: Manages heap blocks returned by
malloc(),calloc(), andrealloc(). - 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;
#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:
NULLPointer:int *p = NULL;explicitly indicates the pointer points to no valid memory address (0). Always checkif (p != NULL)before dereferencing, and initialize pointers toNULLto avoid wild pointers (uninitialized garbage addresses) or dangling pointers (pointing to freed/out-of-scope memory).void *(Generic Pointer): Can hold the address of any data type, but must be cast to a concrete pointer type before dereferencing or performing pointer arithmetic.
6.9 Pointer arithmetic
Pointer arithmetic scales automatically by the size of the pointed-to type (sizeof(*ptr)), not by raw single bytes!
| Operation | Meaning | Result Address (int *p = 1000) | Valid? |
|---|---|---|---|
p + k or p - k | Advances or retreats p by k elements (k * sizeof(*p) bytes) | p + 3 -> 1000 + 3 * 4 = 1012 | Yes |
p++ / p-- | Moves p to next or previous element | p++ -> 1004 | Yes |
q - p (same array) | Number of elements between two pointers of same type | (1012 - 1000) / 4 = 3 elements | Yes |
p == q, p < q | Compares memory positions within same array or NULL | 1 or 0 | Yes |
p + q, p * 2, p / 2 | Adding, multiplying, or dividing addresses | Meaningful address does not exist | Illegal (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]).
| Aspect | Array Name (int arr[5]) | Pointer Variable (int *ptr) |
|---|---|---|
| Modifiability | Constant address; arr++ or arr = ptr is illegal | Modifiable lvalue; ptr++ and ptr = arr are valid |
sizeof Result | sizeof(arr) returns total array bytes (5 * 4 = 20) | sizeof(ptr) returns pointer variable size (4 or 8 bytes) |
| Element Access | arr[i] is compiled identically as *(arr + i) | ptr[i] is compiled identically as *(ptr + i) |
Key Pointer–Array Equivalences:
arr==&arr[0]arr + i==&arr[i]*(arr + i)==arr[i]==i[arr](becausea[b]is defined as*(a + b))- For a 2D array
int m[R][C],*( *(m + i) + j )accessesm[i][j].
Worked Examples
1
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:
a[3]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.
Address(a[3])= 2012Address(b[2][3])= 2044
2
Trace the output of the following C program that uses pointers and pointer arithmetic to traverse and modify an integer array:
#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:
ppoints tonums[0](10).qpoints tonums[3](40).- Pointer subtraction
q - preturns the element distance (not bytes):3 - 0 = 3. So the first line printsdiff=3.
Tracing Dereferences and Updates:
*p += *(p + 3);modifiesnums[0]:nums[0] = nums[0] + nums[3] = 10 + 40 = 50.p += 2;advancespby 2intelements fromnums[0]tonums[2](30).- Now
nums[0]is50,*pisnums[2](30), and*qisnums[3](40).
Output:
diff=3
p0=50 p2=30 *q=403
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:
- Find string length
lenby counting characters untils[len] == '\0'. - Initialize
left = 0andright = len - 1. - While
left < right: ifs[left] != s[right], markis_pal = 0andbreak; otherwise advanceleft++andright--.
#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'), solen = 5. left = 0 ('m'),right = 4 ('m')-> match!left = 1 ('a'),right = 3 ('a')-> match!left = 2,right = 2->left < rightis false; loop ends withis_pal = 1.
Output: len=5 palindrome=1 ("madam" is a palindrome of length 5).
Exercises
Exercises — Array and Pointer
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.
Address(grid[1][3]) = 5064.
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): copiessintod.strcat(d, s): appendssto the end ofd.strcmp(s1, s2): compares ASCII codes (0if equal, negative ifs1 < s2, positive ifs1 > s2).
Tracing the Snippet:
strcat(a, b)changesafrom"Institute of Engineering"to"IOETU".strlen("IOETU")is5.strcmp("abc", "abd")compares'c'(99) vs'd'(100), returning a negative integer (typically-1, i.e.,< 0).
Output: IOETU 5 followed by a negative integer (< 0, typically -1 from 99 - 100).
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:
- 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). sizeofBehavior:sizeof(arr)returns the total bytes of the entire array (N * sizeof(type)), whereassizeof(ptr)returns only the pointer's own address size (4 or 8 bytes).- Storage: Declaring
int arr[5];allocates space for 5 integers; declaringint *ptr;allocates space only for one address.
Pointer-Notation Sum Loop:
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.
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}).
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 + 2advances2 * 8 = 16bytes -> address3000 + 16 = 3016. - For
int *a = 3000,int *b = 3020(sizeof(int) = 4):b - a = (3020 - 3000) / 4 = 20 / 4 = 5elements.
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.
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:
NULLPointer: Explicitly assigned the null pointer constant (NULL), guaranteeing it points to no valid object and can be safely tested withif (p != NULL).- Uninitialized (Wild) Pointer: A local pointer declared without initialization (
int *p;) holding an arbitrary garbage address; dereferencing it causes crashes or silent memory corruption. 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.
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.