BIT102 ยท 2080 ยท 5 marks
What is pointer? Explain the similarity between array and pointer in brief.
What is pointer? Explain the similarity between array and pointer in brief. [5]
Quick answer
A pointer is a variable that stores the memory address of another variable rather than storing a direct value. It "points to" the location in memory where data is stored.
Pointer and Its Similarity with Array
What is a Pointer?
Syntax:
data_type *pointer_name;
Example:
int a = 10;
int *p;
p = &a; // p holds the address of variable a
Here, &a gives the address of a, and *p (dereferencing) gives the value stored at that address, i.e., 10.
Similarity Between Array and Pointer
In C, arrays and pointers are closely related. The key similarities are:
1. Array Name as a Pointer
The name of an array acts as a constant pointer to the first element of the array.
int arr[5] = {10, 20, 30, 40, 50};
int *p = arr; // p points to arr[0]
Here, arr and &arr[0] are equivalent.
2. Accessing Elements
Array elements can be accessed using pointer notation, and pointer elements can be accessed using array notation.
| Array Notation | Pointer Notation | Meaning |
|---|---|---|
arr[0] | *p or *(p+0) | First element |
arr[1] | *(p+1) | Second element |
arr[i] | *(p+i) | i-th element |
printf("%d", arr[2]); // Output: 30
printf("%d", *(p+2)); // Output: 30 (same result)
3. Pointer Arithmetic
Both arrays and pointers support arithmetic operations like increment and decrement to traverse elements.
p++; // moves to the next element (next memory address)
4. Address Relationship
For an array arr:
arr=&arr[0](address of first element)arr + 1=&arr[1](address of second element)arr + i=&arr[i](address of i-th element)
Key Difference (Note)
Although similar, an array name is a constant pointer -- its address cannot be changed, whereas a pointer variable can be reassigned to point to different locations.
p = p + 1; // Valid
arr = arr + 1; // ERROR: array name is a constant pointer
In summary, arrays and pointers are interchangeable in many contexts in C, making pointer knowledge essential for efficient array manipulation.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.