0

I'm trying to create a variable size 3D VLA, I've seen the algorithm for writing a variable 2D arrays and tried to do it for 3D and facing the error segmentation fault and core dumped here is the code I wrote:

#include <iostream>
using namespace std;

int main (){
double ***array;
int columns,rows,d3;
cin>>columns>>rows>>d3;
array = new double **[d3];
for (int i=0;i<d3;i++){
    array[i] = new double *[rows];
}

for (int i=0;i<d3;i++){
    for (int j=0;j<rows;j++){
        array[i][j] = new double [columns];
    }
}

for (int i=0;i<d3;i++){
    for (int j=0;j<rows;j++){
        delete [] array[i][j];
    }
}

for (int i=0;i<d3;i++){
    delete [] array[i];
}

delete[]array;

int p=0;
for (int k=0;k<d3;k++){
    for (int i=0; i<rows;i++){
        for (int j=0; j<columns; j++){
            array [k][i][j] = 0;
            p =p+1;
        }
    }
}
cout<<p;
}
  • 1
    ok, so you allocate everything, then delete everything and then try to store something after you deallocated everything? – PeterT Jul 14 '16 at 10:05
  • I'm allocating the space first, then deleting the excess space and trying to initialize the array. works fine for the below example though ` double **array = NULL; array = new double *[n]; for (int i=0;i – udaysheel zupudi Jul 14 '16 at 10:09
  • You might as well use a `std::vector>>` and quit the manual memory management. – PaulMcKenzie Jul 14 '16 at 10:12
  • *I've seen the algorithm for writing a variable 2D array* -- Well, if you got that code from one of these "algorithms", you are using one of the worst ways of creating such an array. You are calling `new` for every single row created, which is unnecessary if the number of columns is the same for each row. See [my answer here](http://stackoverflow.com/questions/21943621/how-to-create-a-contiguous-2d-array-in-c/21944048#21944048) – PaulMcKenzie Jul 14 '16 at 10:18
  • @udaysheelzupudi no, that second example you posted in your comment is equally as wrong. Try using larger values for `n` and `m` and it will crash all the same. – PeterT Jul 14 '16 at 10:47
  • Thanks for the feedback guys :) – udaysheel zupudi Jul 14 '16 at 12:41

0 Answers0