Explain the relationship between pointers and one-dimensional arrays.
5 marks
Answer in brief
An array contains its elements, while a pointer can identify an element. Their close relationship makes pointer-based traversal possible, but they are not identical types.
Example
int a[3] = {4, 5, 6};
int *p = a;
Indexed and indirect access
For a valid index i, a[i] means *(a + i). With p pointing at the first element, p[i] and *(p + i) also access that element. The sample visits all three values through p and prints 4, 5 and 6.
Important differences
The array declaration reserves storage for all three ints; declaring p reserves only a pointer object.
p can be assigned another compatible address. The array name is not a modifiable pointer variable that can be incremented.
sizeof a gives the whole array size where the actual declaration is visible, while sizeof p gives the pointer size.
&a has a pointer-to-array type, which differs from the pointer-to-element type produced by a in most expressions.
Function connection
A parameter written int a[] adjusts to int *a. That parameter does not retain the caller’s complete array length. Pass a suitable count separately and keep every access within the actual array.
Complexity
A direct valid access takes O(1) time in the usual model. Traversing n elements through a pointer still takes O(n): pointer notation does not remove the need to visit every element. This traversal uses O(1) auxiliary space beyond the array.
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
int a[3] = {4, 5, 6};
int *p = a;
for (int i = 0; i < 3; ++i) { printf("%d\n", *(p + i)); }
return 0;
}
Sample input and output
This example uses values already written in the program.
Output
4
5
6
Related exam questions
Related questions in the pointers arrays category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
June 2022 · Q4(b) · 8 marks
What is a pointer? Write a C program to sum array elements using a pointer.