如何在C中构造结构的指针数组?

问题描述

使用指针结构的动态数组时遇到问题。似乎在循环数组的末尾只有2个指针。我不知道为什么。我是C和低级人员的新手。我正在寻求帮助!您能解释一下为什么会这样吗?

enter image description here

#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;
}