for a school project, we have to create a maze in c, I'm a beginner in that language, so I'm stuck at the very beginning: creating an array dynamically...
I read about malloc and calloc, and tried to use it but with no success...
here is my code:
/* define maze structure */
typedef struct _maze_t {
int m, n;
char **array;
} Maze;
void constructorArray(int m,int n)
{
array = malloc(m * sizeof *array);
for(i=0;i<m;i++){
array[i]=(char *) malloc(n*sizeof(char));
}
array = calloc(m, sizeof *array);
for (i=0; i<m; i++){
array[i] = calloc(n, sizeof *(array[i]));
}
}
void createMaze(int ncolumn, int mlign)
{
int m=mlign;
int n=ncolumn;
int counter=0;
constructorArray(m,n) ;
char **array;
for(i=0;i<m;i++)
{
for(y=0;y<n;y++)
{
array[i][y]=counter;
counter++;
}
}
}
int main()
{
createMaze(100,100);
return 0;
}
Could someone explain to me how to do it right?
It seems you have some believes that are incorrect.
First, you do no correctly declare your C functions:
constructorArray(m,n)
should be:
void constructorArray(int m, int n)
Then it seems that you think a constructor will be called automatically in C, which is not so, so simply writing array[m][n]
in CreateMaze
won't work. You should write:
char **array; // it will be allocated dynamically
and then have your function:
char **constructorArray(int m, int n)
{
char **array= malloc(m*sizeof(char *));
for(int i=0; i<m; i++)
array[i]= malloc(n*sizeof(char));
return array;
}
which you now can call as:
char **array= constructorArray(m, n);
Note: your use of the array suggests an array of ints could be more sutiable.