如何为结构内的数组重新分配内存

时间:2019-06-26 18:59:46

标签: c struct

在下面的代码中,当使用

重新分配内存时
g->alist[u] = realloc(g->alist[u], sizeof(struct successors) +
sizeof(int) * (g->alist[u]->len - 1)) 

如何使用

将数字添加到list[]
g->alist[u]->list[g->alist[u]->d++] = v

是否已初始化为list[1]

struct graph {
    int n;
    int e;
        struct successors {
            int d;
            int len;
            char is_sorted;
            int list[1];        
         } *alist[1];
};
typedef struct graph *Graph;

Graph graph_create(int n)
{

    Graph g;
    int i;

    g = malloc(sizeof(struct graph) + sizeof(struct successors*) * (n - 1));
    assert(g);
    g->v = n;
    g->e = 0;

    for (i = 0; i < n; i++)
    {
        g->alist[i] = malloc(sizeof(struct successors));
        assert(g->alist[i]);

        g->alist[i]->d = 0;
        g->alist[i]->len = 1;
        g->alist[i]->is_sorted = 1;
    }

    return g;
}

void graph_add_edge(Graph g, int u, int v)
{
    assert(u >= 0);
    assert(u < g->v);
    assert(v >= 0);
    assert(v < g->v);
    while(g->alist[u]->d >= g->alist[u]->len)  
    {
        g->alist[u]->len *= 2;
        g->alist[u] = realloc(g->alist[u], sizeof(struct successors) + 
        sizeof(int) * (g->alist[u]->len - 1));
    }
    g->alist[u]->list[g->alist[u]->d++] = v;
    g->alist[u]->is_sorted = 0;
    g->e++;
}

0 个答案:

没有答案