Pointer to One and Two-Dimensional Arrays
Basic Idea of
Pointer and Array Relationship
An array name acts like a pointer to its first element.
If arr is an array, arr is
equivalent to &arr[0], and its type is Type* (e.g., int* for an array of
integers).
That means:
int arr[5] = {10, 20, 30, 40, 50};
Here:
- arr
→ address of first element → same as &arr[0]
- *arr
→ value of first element → same as arr[0]
Example:
#include <iostream>
using namespace std;
int main() {
int arr[5] = {10, 20, 30, 40, 50};
cout << "arr = " << arr << endl; // Address of arr[0]
cout << "&arr[0] = " << &arr[0] <<
endl;
cout << "*arr = " << *arr << endl; // 10
cout << "*(arr + 1) = " << *(arr + 1) <<
endl; // 20
}
Example:
#include <iostream>
int main() {
int arr[5] = {10, 20, 30, 40, 50};
int* p = arr; // p
points to arr[0]
for (int i = 0; i < 5; ++i) {
std::cout << *(p + i) <<
" "; // Access elements using pointer arithmetic
}
std::cout << std::endl;
return 0;
}
Output: 10 20 30 40 50
Pointer to
One-Dimensional Array
A pointer to an array can be
declared explicitly and assigned the address of an array.
Syntax: Type* ptr = array;
Example:
#include <iostream>
using namespace std;
int main() {
int arr[5] = {2, 4, 6, 8, 10};
int *p = arr;
for(int i = 0; i < 5; i++) {
cout << "Element "
<< i << " = " << *(p + i) << endl;
}
}
Output:
Element 0 = 2
Element 1 = 4
Element 2 = 6
Element 3 = 8
Element 4 = 10
Pointer to
Two-Dimensional Array
- stored
as a contiguous block of memory in row-major order (i.e., rows are stored
one after another).
- declared
as a pointer to an array of COLS elements.
Syntax:
Type (*ptr)[COLS];
- For
an array int arr[ROWS][COLS], the element at arr[i][j] is located at
memory address:
&arr[i][j] =
base_address + (i * COLS + j) * sizeof(int)
- The
array name arr is a pointer to the first row (type: int (*)[COLS]), not a
simple int*.
In 2D array:
int a[2][3] = {
{10, 20, 30},
{40, 50, 60}
};
Here:
- a
→ address of the first row → same as &a[0]
- a
+ 1 → address of second row → same as &a[1]
- *(a
+ 0) → address of first element of first row → same as a[0]
- *(*(a
+ 0) + 1) → second element of first row → same as a[0][1]
Example: Pointer to a 2D Array
include <iostream>
int main() {
int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};
int (*ptr)[3] = arr; // Pointer to an array of 3 integers
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
std::cout << ptr[i][j]
<< " "; // Access elements
}
std::cout << std::endl;
}
// Output:
// 1 2 3
// 4 5 6
return 0;
}
===============================================
0 Comments