su*******@yahoo.com napsal:
Hi ,
I am trying to alllocate a 2D array of strings and returning it
to a functiion, I get a memory access error. What is wrong with the
program?
int main3DArray( char *** x);
int main()
{
int i,j;
char **p;
main3DArray(&p);
for(i=0,j=0; i< 5;j++, i++)
// cout << p[i][j] << endl;
return 0;
}
int main3DArray( char *** x)
{
const int l=10;
const int m=10;
const int n=10;
int j,i;
x = (char ***)malloc ( n * sizeof (char ** ));
for (i =0; i< n; i++ )
x[i] = (char **)malloc (m * sizeof (char * ));
for (i =0; i< n; i++ )
for ( j=0; j<m; j++)
{ x[i][j] =(char*) malloc (l * sizeof(char));
strcpy(x[i][j],"TEST"); // I am trying to allocate a 2d array of
"TEST"
}
return 0;
}
Thanks
Sledge
I think the problem is, that you are making 3d array and working with
2d array. It mixed somehow.
It seems, you want 2d array of char*. O.K., you need char *** p in
main. (2 pointers for 2 dimensions and 1 pointer level to char* data
item).
Try it this way:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main3DArray( char **** x);
int main()
{
int i,j;
char ***p;
main3DArray(&p);
for (i=0,j=0; i< 5;j++, i++)
printf("%s\n", p[i][j]);
// cout << p[i][j] << endl;
return 0;
}
int main3DArray( char **** x)
{
const int l=10;
const int m=10;
const int n=10;
int j,i;
(*x) = (char ***)malloc ( n * sizeof (char ** ));
for (i =0; i< n; i++ )
(*x)[i] = (char **)malloc (m * sizeof (char * ));
for (i =0; i< n; i++ )
for ( j=0; j<m; j++)
{
(*x)[i][j] =(char*) malloc (l * sizeof(char));
strcpy((*x)[i][j],"TEST"); // I am trying to allocate a 2d
array of "TEST"
}
return 0;
}
However there is no need to make the main3DArray function to return
always 0 and return the real result in it's parameter. This is more
readable:
char*** Make3DArray(void)
{
const int l=10;
const int m=10;
const int n=10;
char*** x;
int j,i;
x = (char ***)malloc ( n * sizeof (char ** ));
for (i =0; i< n; i++ )
x[i] = (char **)malloc (m * sizeof (char * ));
for (i =0; i< n; i++ )
for ( j=0; j<m; j++)
{
x[i][j] =(char*) malloc (l * sizeof(char));
strcpy(x[i][j],"TEST"); // I am trying to allocate a 2d
array of "TEST"
}
return x;
}
Anyway, you should use some better (and much much more readable)
solutions in C++, for example std::vector, std::string etc.