Explanation
A pointer is a variable in C that holds the memory address of another variable. Pointers are used to work with memory addresses, access data indirectly, and dynamically allocate memory. They are a powerful feature in C and are commonly used in various programming tasks.
To work with a double-dimensional array using pointers, you can use a pointer to a pointer, also known as a pointer to an array. Here's how you can use pointers to print all the elements of a two-dimensional array:
#include <stdio.h>
int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int rows = 3;
int cols = 3;
// Pointer to a pointer (pointer to an array of integers)
int (*ptr)[cols] = matrix;
// Use pointer to iterate through the 2D array
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", ptr[i][j]);
}
printf("\n");
}
return 0;
}
In this program:
-
We have a 3x3 two-dimensional integer array called matrix containing some values.
-
We declare’ ptr’ as a pointer to an array of integers (i.e., a pointer to an array with cols elements).
-
We set ‘ptr’ to point to the matrix, effectively converting the two-dimensional array into a one-dimensional array of arrays.
-
We use ‘ptr’ to iterate through the two-dimensional array, accessing each element and printing it.
This program prints all the elements of the two-dimensional array using pointers. Pointers are used to navigate the array elements by accessing their memory addresses indirectly.