创建一个动态数组并初始化它
Create a dynamic array and initialize it
对于一个学校项目,我们必须在 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中会自动调用一个构造函数,其实不然,所以简单地在CreateMaze
中写array[m][n]
是行不通的。你应该写:
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);
注意:您对数组的使用表明整数数组可能更合适。
对于一个学校项目,我们必须在 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中会自动调用一个构造函数,其实不然,所以简单地在CreateMaze
中写array[m][n]
是行不通的。你应该写:
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);
注意:您对数组的使用表明整数数组可能更合适。