-1

I am new to coding, so I am simply trying to create a function that allows the user to create a two-dimensional array by specifying the number of rows and columns and the content of the array elements. The function is supposed to return the array through an array of pointers, and later in main(), I call the function and display the contents of the array with a for loop. When I run the application, the function appears to run correctly but the contents of the array is not displayed. The process returns "-1073741819 (0xC0000005)". What does this error mean and how do I solve it? Moreover, are there any cleaner and more effective ways to return an array from a function? Also, I think the issue is in the for loop in main() because I commented it out and the process then returned 0.

void CreateArray(int **ptr2ptr) {
cin >> rows;
cin >> columns;

int TheArray[rows][columns];

     //fill array
for (int i = 0; i < rows; i++)
 {
        cout << "Enter values for row  " << i +1 << ":" << endl;

    for (int k =0; k < columns; k++)
    {
        int x;
        cin >> x;
        TheArray[i][k]= x;
    }
 }
    int *array4ptrs[rows*columns];
    array4ptrs[rows * columns] = new int[rows*columns];

    // fill array of pointers
    for (int c=0; c< (rows * columns); c++) {
       array4ptrs[c] = TheArray[c];
    }
 ptr2ptr = array4ptrs;
}

int main() {

    int **MyPtr2Ptr;
CreateArray(MyPtr2Ptr);


for (int z = 0; z <sizeof (MyPtr2Ptr); z++) {
        cout << *MyPtr2Ptr[z] << endl;
}


    for (int z = 0; z < sizeof (MyPtr2Ptr);z++) {
    delete MyPtr2Ptr[z];
}

}
Lucas C
  • 11
  • 3
  • 2
    Consider learning from a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) instead of coding randomly. 0xC0000005 is an error code, which means "access violation", which means that you are accessing memory, that you don't have access to. – Algirdas Preidžius Jun 10 '19 at 18:05
  • 1
    Posting code that is incomplete and therefore does not compile is not going to help you. Code::Blocks includes a debugger - that will help you a lot. – Clifford Jun 10 '19 at 18:07

1 Answers1

0

Many issues.

CreateArray(MyPtr2Ptr);

This passes the double pointer by value, so the original variable is not modified.

void CreateArray(int **ptr2ptr)

This function modifies a local copy of the variable, not the original one. Pass by reference:

void CreateArray(int **& ptr2ptr)

Or, better, forget completely that C stuff and use STL. And use your debugger to find out, a good GUI value is the debugger's value, not the compiler's.

int TheArray[rows][columns];

Variable size array, not C++. And trouble next when you convert a double array to a single one.

Michael Chourdakis
  • 10,345
  • 3
  • 42
  • 78