Reputation: 2160
I wanted to create a function that creates a two dimensional dynamic array. so i wrote:
#include<iostream>
using namespace std;
void make_mat (double *** , int, int);
int main(){
int m = 3, n = 4;
double **a;
make_mat(&a,m,n);
for (int i = 0; i < m; i++)
for (int j = 0; j < m; j++)
cin >> a[i][j];
for (int i = 0; i < m; i++){
for (int j = 0; j < m; j++)
cout << a[i][j] << '\t';
cout << endl;
}
return 0;
system("pause");
}
void make_mat( double ***x , int m , int n){
*x = new double *[m];
for (int i = 0; i < m; i++){
*x[i] = new double [n];
}
}
There's no syntax errors in the codes but i get following error after compiling:
Unhandled exception at 0x003657E6 in ConsoleApplication20.exe: 0xC0000005: Access violation writing location 0xCCCCCCCC.
Totally this is not a good way for creating a function that creates two dimensional dynamic array. is there any better idea or any correction on the code above?
Upvotes: 0
Views: 53
Reputation: 75062
*x[i]
is equivalent to *(x[i])
, which is equivalent to x[i][0]
.
You should use (*x)[i]
instead of *x[i]
in the function make_mat()
.
Upvotes: 2