c - 初始化 union 类型的二维数组(整数或字符)

标签 c arrays matrix 2d unions

所以我正在尝试创建一个大小为行 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 类型,不是 intchar .

如果你想分配一个整数:

myBoard->boardSpaces[0][0].ajacentMines = 5;

对于一个字符:

myBoard->boardSpaces[0][0].mineHere= '5';

union 是内存中同一位置的多种解释 - 但要使用的解释必须由代码提供。

关于c - 初始化 union 类型的二维数组(整数或字符),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29836842/

相关文章:

javascript - 在javascript中循环移动数组

java - 如何连接矩阵中的多行

c - do while(0) or if else 哪一个适合单一导出点?

c - 删除链表中的元素,直到找到单词

java - 如何从字符串数组或数组列表创建一个字符串?

java - ojalgo 中的 QR/SVD 分解是否需要与列一样多的行?

matrix - 在 Julia 中将矩阵提升为幂

c - 即使每个变量都满足条件,它也总是返回 FALSE

c - 使用 CMake 时链接 PETSc 程序时出现的问题

c - 使用 %c 或 %s 扫描