gpt4 book ai didi

c - 设置结构体指针

转载 作者:行者123 更新时间:2023-11-30 19:23:59 28 4
gpt4 key购买 nike

我在弄清楚如何启动结构指针数组时遇到问题。我基本上想做的是循环遍历结构指针数组,并为每个指针做一些工作。

结构代码:

typedef double Align;
union header {
struct {
union header * p, *prev;
unsigned size;
} s;
Align x;
};

typedef union header Header;

我无法工作的代码如下:

Header * freelist[NRQUICKLISTS]; /* Listan med  */

void init() { /* call this once in the beginning */
int i;
for (i = 0; i < NRQUICKLISTS-1; i++) {
freelist[i]->s.p = freelist[i]; /* <-- this line cause Segmentation fault */
freelist[i]->s.size = 0;
}
freelist[i] = &base;
freelist[i]->s.p = freep = &base; /* cirkulär lista */
freelist[i]->s.size = 0;
}

最佳答案

您需要先为指针分配内存,然后才能使用它们:

for (i = 0; i < NRQUICKLISTS-1; i++) {
freelist[i] = new Header;
freelist[i]->s.p = freelist[i]; /* <-- this line cause Segmentation fault */
freelist[i]->s.size = 0;
}

另外,我建议您采用 C++ 方式进行操作 - 即使用 std:vector 而不是数组。

编辑:

对于 C,使用 malloc:

for (i = 0; i < NRQUICKLISTS-1; i++) {
freelist[i] = malloc(sizeof(Header));
freelist[i]->s.p = freelist[i]; /* <-- this line cause Segmentation fault */
freelist[i]->s.size = 0;
}

关于c - 设置结构体指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8512147/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com