如何解决如何在C中构造结构的指针数组?
使用指针结构的动态数组时遇到问题。似乎在循环数组的末尾只有2个指针。我不知道为什么。我是C和低级人员的新手。我正在寻求帮助!您能解释一下为什么会这样吗?
#include <stdlib.h>
struct Coordinates {
short x;
short y;
};
const short BOARD_SIZE = 8;
const short MAX_SIZE = 10;
int main() {
struct Coordinates **possible_moves = malloc(MAX_SIZE * sizeof(struct Coordinates));
for (short i = 0; i < BOARD_SIZE; ++i) {
struct Coordinates *current_coordinates = malloc(sizeof(struct Coordinates));
current_coordinates->x = i;
current_coordinates->y = i;
possible_moves[i] = current_coordinates;
}
return 0;
}
解决方法
要分配给possible_moves
的数组的元素是指针,因此分配大小应该是指针之一,而不是结构之一。
换句话说,
struct Coordinates **possible_moves = malloc(MAX_SIZE * sizeof(struct Coordinates));
应该是
struct Coordinates **possible_moves = malloc(MAX_SIZE * sizeof(struct Coordinates*));
或
struct Coordinates **possible_moves = malloc(MAX_SIZE * sizeof(*possible_moves));
,
或者您可以这样做:
#include <stdlib.h>
struct Coordinates {
short x;
short y;
};
const short BOARD_SIZE = 8;
const short MAX_SIZE = 10;
int main() {
// struct Coordinates * instead of struct Coordinates **
struct Coordinates *possible_moves = (Coordinates *)malloc(MAX_SIZE * sizeof(struct Coordinates));
for (short i = 0; i < BOARD_SIZE; ++i) {
// struct Coordinates instead of struct Coordinates *
struct Coordinates current_coordinates = {i,i};
possible_moves[i] = current_coordinates;
}
free(possible_moves);
return 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。