【问题标题】:create flexible array size in struct在结构中创建灵活的数组大小
【发布时间】:2021-12-28 18:03:33
【问题描述】:

嗨,我有这些结构代码
我需要使我的 head[] 数组大小灵活
例如,如果我的头数组大小为 9,我如何将其扩展为 10?!

struct Graph
{
  // An array of pointers to Node to represent an adjacency list
  struct Node *head[N];
};

// Data structure to store adjacency list nodes of the graph
struct Node
{
  int dest, weight;
  struct Node *next;
};

如何创建具有灵活头部数组大小的结构图?

【问题讨论】:

  • struct Graph中还有其他字段吗?如果没有,你就不需要它。
  • 如果您使用灵活数组成员结构,您可以使用realloc() 扩展它。
  • @dbush 尽管可能不需要图形,但我发现在处理链表时将头节点指针存储在与节点不同的结构中更容易。以这种方式管理似乎更容易。
  • 但是我不明白的是为什么你在处理链表时会有一个相邻的列表数组?
  • @TedLyngmo 感谢 ted 我将为我的新问题创建新问题

标签: c visual-studio-code struct graph adjacency-list


【解决方案1】:

具有灵活数组成员的struct 通常有一个成员跟踪数组的大小,所以我假设它看起来像这样:

struct Graph {
    size_t nodes;
    struct Node *head[];
};

要为这样的struct 分配内存,您需要调用malloc 并将sizeof(Graph)(其中灵活成员的范围计为0)和sizeof(struct Node*[the_number_of_node_pointers_you_want]) 相加。

例子:

struct Graph *Graph_create(size_t nodes) {
    struct Graph *g = malloc(sizeof *g + sizeof(struct Node*[nodes]));
    if(g) g->nodes = nodes;
    return g;
}

如果你以后想扩展灵活数组,你可以用类似的方式使用realloc

// this returns true or false depending on if expansion succeeded
bool Graph_expand(struct Graph **g, size_t nodes) {
    if(*g && (*g)->nodes < nodes) {
        struct Graph *ng = realloc(*g, sizeof *ng + sizeof(struct Node*[nodes]));
        if(ng) {
            *g = ng;
            (*g)->nodes = nodes;
            return true;
        }
    }
    return false;
}

Demo

在扩展数组时要注意:realloc 如果不能就地扩展分配,可能会移动内存。如果发生这种情况并且您有任何指针指向您的旧 Graph 对象,它们将被该 realloc 无效。

【讨论】:

  • 你知道如何释放所有的图结构吗?
  • @noorshein 当然,对于您从malloc 获得的每一个指针,您都是free。如果你 realloc 那个指针,你 free 是从 realloc 返回的东西。因此,对于每个分配都应该有一个免费的。这是一对一的关系。
  • 对不起,但我不明白,如果我想删除一个特定的头节点,它是系列我该怎么做,例如 2->5(weight 3) head[2] 和所有节点与此头像有关
  • 你能在这里和我讨论这个问题的新主题吗>>
  • 你能在这里查看我的这个问题的新主题>> link 并尝试解决它吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-12
  • 1970-01-01
  • 2011-03-04
  • 1970-01-01
  • 2017-08-13
  • 2010-09-20
相关资源
最近更新 更多