【问题标题】:How to construct array of pointer of structs in C?如何在C中构造结构指针数组?
【发布时间】:2020-10-22 19:47:13
【问题描述】:

我在处理指针结构的动态数组时遇到问题。似乎在循环数组的末尾只有 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 = malloc(MAX_SIZE * sizeof(struct Coordinates)); 中有错字。你的意思是 sizeof(struct Coordinates *)

标签: arrays c pointers struct


【解决方案1】:

要分配给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));

【讨论】:

    【解决方案2】:

    或者你可以这样做:

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

    【讨论】:

      猜你喜欢
      • 2019-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-21
      • 2013-04-18
      相关资源
      最近更新 更多