【发布时间】:2023-03-27 11:41:01
【问题描述】:
我正在尝试将字符放入我的二维数组。我已经定义了这些对象:
typedef struct board {
char* board[25][80];
}Board;
typedef struct obstacleA {
int* x;
int* y;
}ObstacleA;
typedef struct obstacleC {
int* x;
int* y;
}ObstacleC;
typedef struct obstacleB {
int* x;
int* y;
}ObstacleB;
typedef struct Star {
int *x;
int *y;
int *power;
}Star;
typedef struct Cross {
int *x;
int *y;
int *power;
}Cross;
我的 spawn 函数为我的对象提供随机数(或坐标)
void spawn(Board* board, Cross* cross, Star* star, ObstacleA* A, ObstacleB* B, ObstacleC* C) {
srand(time(NULL));
cross->x = (1 + rand() % 24);
cross->y = (1 + rand() % 79);
star->x = (1 + rand() % 24);
star->y = (1 + rand() % 79);
A->x = (1 + rand() % 24);
A->y = (1 + rand() % 79);
B->x = (1+ rand() % 24);
B->y = (1+ rand() % 79);
C->x = (1 + rand() % 24);
C->y = (1 + rand() % 79);
putBoard(&board, &cross, &star, &A, &B, &C);
}
putBoard 函数将字符放置在正确的坐标中:
void putBoard(Board* board, Cross* cross, Star* star, ObstacleA* A, ObstacleB* B, ObstacleC* C) {
board->board[*star->x][*star->y] = '*';
board->board[*cross->x][*cross->y] = '+';
board->board[*A->x][*A->y] = 'A';
board->board[*B->x][*B->y] = 'B';
board->board[*C->x][*C->y] = 'C';
}
然而,在运行程序时,我得到一个“抛出异常:写访问冲突。
板是 0x21C3BD2。”
在“board->board[*C->x][*C->y] = 'C';”行。
【问题讨论】:
-
你真的想要一个由
char指针组成的二维数组吗? -
分配内存以便那些
char*指向一些内存并且你写给他们。&board不能有Board*类型,如果board本身是Board*- 它将是Board**。 -
@coderredoc 或仅分配给 string 文字
-
结构中的整数也一样。我认为你的结构中根本不需要指针。
-
如果你只使用例如的第一个元素
star->x,那为什么要用指针开头呢?为什么Star结构的x成员是指针?