Rubby Rubby - 3 months ago 7
C++ Question

When casting return from new int[10][3] to int** pointer, the program using it outputs : Segmentation fault: 11?

Why this program outputs: Segmentation fault: 11

#include <iostream>
using namespace std;
int main(){
int **a = (int**)new int[10][3];
a[0][0] = 1; a[0][1] = 2; a[0][2] = 3;
cout << a[0][0] << "," << a[0][1] << "," << a[0][2];
return 0;
}

Answer

Change this declaration

int **a = (int**)new int[10][3];

to

int ( *a )[3] = new int[10][3];

Otherwise pointers int ** and int ( *a )[3] returned by the operator new are incompatible.

The problem is that in expression a[0] when a has type int ** the compiler tries to read the allocated non-initialized memory as a valid value of pointer of type int *.

Also you should delete the pointer at the end of the program

delete [] a;

Another approach is the following

int **a = new int * [10];

for ( size_t i = 0; i < 10; i++ ) a[i] = new int[3];

In this case the allocated memory is freed the following way

for ( size_t i = 0; i < 10; i++ ) delete [] a[i];
delete [] a;