【问题标题】:How to create linked list of arrays in c如何在c中创建数组的链表
【发布时间】:2021-07-30 16:35:37
【问题描述】:

我想创建一个包含可变长度数组的链表int A[n][n]

我尝试这样做,但我收到错误 Incomplete type is not allowed

struct Node {
 int A[n][n];
 struct Node* next;
};

有没有办法在c中做到这一点?

【问题讨论】:

  • 你不能做int A[n][n]。其余的看起来不错。
  • 对于可变长度数组,您需要使用指针并通过一些构造函数为您的结构动态分配它们。

标签: arrays c linked-list variable-length-array


【解决方案1】:

您需要使用在堆上分配的int ** 以获得可变长度。为此,您需要一个构造函数和一个析构函数。我还添加了在构造函数中指定下一个节点的功能。

struct Node{
    size_t size;
    int **A;
    struct Node* next;
};

void construct_node(struct Node *node, size_t n, struct Node *next_node) {
    node->size = n;
    node->A = malloc(n * sizeof(int *));
    for (size_t i = 0; i < n; i++) {
        node->A[i] = malloc(n * sizeof(int));
    }
    node->next = next_node;
}

void destruct_node(struct Node *node) {
    for (size_t i = 0; i < node->size; i++) {
        free(node->A[i]);
    }
    free(node->A);
    // You probably also want to call destruct_node on the next node to free the entire list:
    // if (node->next) destruct_node(node->next);
}

完成此操作后,创建节点将需要以下代码:

int size = 10;
struct Node your_node;
construct_node(&your_node, size, NULL);

// Do your stuff with the node

destruct_node(&your_node);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-20
    • 1970-01-01
    • 2012-02-28
    • 2013-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多