所以我正在尝试创建一个大小为行 x 列的二维数组。我为它分配了空间(或者至少我认为),现在我正在尝试初始化它或至少测试它以查看它是否可以保存值。但是,每当我输入 union 应包含两者的 int 或 char 时,我都会收到类型不兼容的错误。
我认为我的 union 有问题,因为我试图在结构中声明矩阵,因为我的错误表明它无法识别我的类型 Mine 来保存整数或字符....或者我只是将值错误地放入二维数组中。
我现在只是想测试并确保我几乎正确地制作了二维数组。
错误
test.c:49:29: error: incompatible types when assigning to type ‘Mine’ from type ‘int’
myBoard->boardSpaces[0][0] = 5;
代码
typedef union
{
int ajacentMines;
char mineHere;
}Mine;
typedef struct boards
{
int rows, columns; //rows and columns to make the array
Mine **boardSpaces; //a void pointer to hold said array
}Board;
Board *createBoard(int rows, int columns)
{
Board *b = malloc(sizeof(Board));
b->rows = rows;
b->columns = columns;
b->boardSpaces = malloc(rows*sizeof(Mine*)); //allocate first dimmension
int i;
for(i = 0; i < rows; i++)
b->boardSpaces[i] = malloc(columns*sizeof(Mine)); //allocate second dimmension
return b;
}
int main()
{
int rows = 3;
int columns = 4;
Board *myBoard = createBoard(rows,columns);
myBoard->boardSpaces[0][0] = 5;
printf("DONE\n");
}
最佳答案
myBoard->boardSpaces[0][0]
是 Mine
类型,不是 int
或 char
.
如果你想分配一个整数:
myBoard->boardSpaces[0][0].ajacentMines = 5;
对于一个字符:
myBoard->boardSpaces[0][0].mineHere= '5';
union 是内存中同一位置的多种解释 - 但要使用的解释必须由代码提供。
关于c - 初始化 union 类型的二维数组(整数或字符),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29836842/