Problem Solving Through C (BCA) 1st Sem Previous Year Solved Question Paper 2022

Practice Mode:
11.

What is a pointer ? How to use pointers with double dimensional array ? Write a program to print all the elements of a two-dimensional array using pointers.

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:

  1. We have a 3x3 two-dimensional integer array called matrix containing some values.

  2. We declare’ ptr’ as a pointer to an array of integers (i.e., a pointer to an array with cols elements).

  3. We set ‘ptr’ to point to the matrix, effectively converting the two-dimensional array into a one-dimensional array of arrays.

  4. 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.