Armeen Parsa
Armeen Parsa

Reputation: 11

How can I use pointers to access the elements of this two-dimensional array?

I have a two dimensional array as follows: char board[3][3] = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};

and I'm accessing its elements as follows:

cout << board[0][0] << board[0][1] << board[0][2] << "\n";
cout << board[1][0] << board[1][1] << board[1][2] << "\n";
cout << board[2][0] << board[2][1] << board[2][2] << "\n";

Now I'd want to create a pointer to this array and access its elements. So here's what I came up with: char (*ptr)[3] = board which doesn't work.

How to access the elements using pointers? 

Upvotes: 0

Views: 85

Answers (1)

Lalit Kumar
Lalit Kumar

Reputation: 134

I will try to give a generalized answer :

like imagine if you have an multidimensional integer array :

int arr[3][3] = {{2,1,2}, {3,4,6}, {2,1,9}};

here . there are 3 rows and 3 columns [3][3]. you might want to know them (size of array, rows and columns) at least in this method.There is one more method that can be used but i am sure, it will go out of scope.

So,

the way you access every element with pointer is :

 for(int *iter = &arr[0][0]; iter != &arr[0][0] + 3 * 3; iter++){
    std::cout << * (iter) << "  " ;
  }

*iter = &arr[0][0] here we are assigning it to the first element and the condition is sert to iter != &arr[0][0] + 3 * 3 here as i knew size is 3 rows 3 columns so i did this , you can do + rows * columns; that would work.

Optiplex@jetta:~/Desktop/PROGRAM/CPP$ ./b.out
2  1  2  3  4  6  2  1  9 

here is the output for you.

Similarly, will do for the character,

CODE FOR CHARACTER :

#include <iostream>
#include <string>

int main(){
  
  char BOARD[3][3] = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};

  for(char * iter = &BOARD[0][0]; iter != &BOARD[0][0] + 3 * 3; iter++){
    std::cout << * (iter) << "  " ;
  }
}

OUTPUT :

Optiplex@jetta:~/Desktop/PROGRAM/CP$ ./b.out
1  2  3  4  5  6  7  8  9

we have used iter as pointer . and iter is kinda abbreviation for iterator (because you are using it to iterate through your array, its nice to name your variables conviently). I hope i helped you, if there is something left please let me know.

Upvotes: 2

Related Questions