LasherHN
February 25th, 2009, 02:39 PM
I'm trying to use some double arrays, one approach that works is this:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int **a;
//get memory
a=new int*[5];
for(int i=0; i<5; i++)
a[i]=new int[5];
//assign
int k=0;
for(int i=0; i<x; i++)
for(int j=0; j<y; j++){
a[i][j]=k;
k++;
}
//print
for(int i=0; i<5; i++){
for(int j=0; j<5; j++){
cout<<a[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
That prints a matrix-like array of 5x5 without any problems.
In another program im doing i need to do that in a separete function like this:
#include <iostream>
#include <cstdlib>
using namespace std;
void arraytest(int ***);
int main() {
int **a;
arraytest(&a);
//print
for(int i=0; i<5; i++){
for(int j=0; j<5; j++){
cout<<a[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
void arraytest(int ***a){
//get memory
*a=new int*[5];
for(int i=0; i<5; i++)
*a[i]=new int[5];
//assign
int k=0;
for(int i=0; i<5; i++)
for(int j=0; j<5; j++){
*a[i][j]=k;
k++;
}
}
But the second code gives me a segmentation error. Could you tell me please what's wrong with it?
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int **a;
//get memory
a=new int*[5];
for(int i=0; i<5; i++)
a[i]=new int[5];
//assign
int k=0;
for(int i=0; i<x; i++)
for(int j=0; j<y; j++){
a[i][j]=k;
k++;
}
for(int i=0; i<5; i++){
for(int j=0; j<5; j++){
cout<<a[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
That prints a matrix-like array of 5x5 without any problems.
In another program im doing i need to do that in a separete function like this:
#include <iostream>
#include <cstdlib>
using namespace std;
void arraytest(int ***);
int main() {
int **a;
arraytest(&a);
for(int i=0; i<5; i++){
for(int j=0; j<5; j++){
cout<<a[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
void arraytest(int ***a){
//get memory
*a=new int*[5];
for(int i=0; i<5; i++)
*a[i]=new int[5];
//assign
int k=0;
for(int i=0; i<5; i++)
for(int j=0; j<5; j++){
*a[i][j]=k;
k++;
}
}
But the second code gives me a segmentation error. Could you tell me please what's wrong with it?