好的,所以我试图将带有字符串元素的2D数组元素传递给struct中的2D数组。我制作了一个代码,但它收到了一个运行时错误。我认为在我试图初始化board2 [i] [j]的代码中存在问题。任何帮助表示赞赏。
char ***board;
int i, j, size;
printf("Enter the size of array:");
scanf("%d", &size);
if((board = (char***)malloc(sizeof(char**)*size))==NULL)
{
printf("Memory Allocation failed\n");
return -1;
}
for(i=0; i<size; i++)
{
if((board[i] = (char**)malloc(sizeof(char*)*size))==NULL)
{
printf("Memory Allocation failed\n");
return -1;
}
for(j=0; j<size; j++)
{
if((board[i][j] = (char *)malloc(sizeof(char)*4))==NULL)
{
printf("Memory Allocation failed\n");
return -1;
}
a = rand() % 2;
b = rand() % 2;
if(a==0 && b==0)
strcpy(board[i][j], "ab");
else if(a && b==0)
strcpy(board[i][j], "Ab");
else if(a==0 && b==1)
strcpy(board[i][j], "aB");
else
strcpy(board[i][j], "AB");
}
struct data{
const char *element;
int visited;
};
void board2_initialize(char ***board, int size)
{
struct data **board2;
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
board2[i][j].element = board[i][j];
board2[i][j].visited = 0;
printf("%s", board2[i][j].element);
}
}
}
编辑:忘记提及初始化将在函数内部发生
答案 0 :(得分:3)
您的分配方式与执行board
数组的方式相同:
struct data **board2 = malloc(sizeof(struct data *) * size);
for(i = 0; i < size; i++)
{
board2[i] = malloc(sizeof(struct data) * size);
for(j = 0; j < size; j++)
{
/* ... */
}
}