对于学校项目,我们必须在 c 中创建一个迷宫,我是该语言的初学者,所以我一开始就被困住了:动态创建一个数组......
我阅读了 malloc 和 calloc,并尝试使用它但没有成功......
这是我的代码:
/* 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;
}
有人可以向我解释如何正确地做吗?
看来你有一些不正确的信念。
首先,您没有正确声明 C 函数:
constructorArray(m,n)
应该:
void constructorArray(int m, int n)
那么似乎您认为在 C 中会自动调用构造函数,但事实并非如此,因此简单地写入array[m][n]
是CreateMaze
行不通的。你应该写:
char **array; // it will be allocated dynamically
然后有你的功能:
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;
}
您现在可以将其称为:
char **array= constructorArray(m, n);
注意:您对数组的使用表明整数数组可能更适合。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句