0

I've been unable to find simple examples of how to define a function that scans in an array then returns a pointer to that array. Here is my code:

#include <iostream>
using namespace std;

int *read() {
  int x[2][2];
  int (*pX)[2][2] = &x;
  int row = 0, col = 0;
  for(int cell = 0; cell < 4; cell++){
      if(cell - (row * 2) >= 2){
      row++;
      }
      col = cell - (2 * row);
      cout << "Cell " << cell << ", row " << row << ", column "<< col << " \n";
      cin >> x[col][row];        
      }
  return pX;
}

But when compiling, I get the error "cannot convert 'int ()[2][2]' to 'int' in return.

What is the correct syntax for returning a single pointer to the whole 2x2 array? Thanks in advance.

David.

David
  • 1
  • 7
    Don't return a pointer or reference to a local temporary object. – masoud Nov 11 '14 at 11:29
  • A pointer to the array has type `int (*)[2][2]`, exactly as you declare `pX` and as the compiler says. A pointer to the first element of the array has type `int (*)[2]`. A pointer to the first element of the first element of the array has type `int*`. But you should not return pointers to local variables, you should probably use `std::vector`. – molbdnilo Nov 11 '14 at 12:19

0 Answers0