C 动态列表问题

标签 c list dynamic

typedef struct {
    long blarg;
} item;

typedef struct 
{
    item* items;
    int size;
} list;

列表和项目结构,相当简单。

list l;
l.size = 3;
realloc(l.items, l.size*sizeof(item));

创建一个列表,分配它容纳 3 个项目。

item thing;
item thing2;
item thing3;

thing.blarg = 1337;
thing2.blarg = 33;
thing3.blarg = 123;

l.items[0] = thing;
l.items[sizeof(item)+1] = thing2;
l.items[(sizeof(item)*2)+1] = thing3;

创建一些项目并将它们添加到列表中...但是打印它们时:

printf("List 0: %ld\n", l.items[0].blarg);
printf("List 1: %ld\n", l.items[sizeof(item)+1].blarg);
printf("List 2: %ld\n", l.items[(sizeof(item)*2)+1].blarg);

List 0: 1337 
List 1: 33 {
List 2: 1953720652 !

哪里出了问题?

最佳答案

您应该更改 l.items[sizeof(item)+1]l.items[(sizeof(item)*2)+1] --> l.items[1]l.items[2]

关于C 动态列表问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18158232/

相关文章:

c - 使用 typedef 在 C 中实现抽象数据类型

c - C 语言中 i = i&1 是什么意思?

java - 为什么 List 接口(interface)的 lastIndexOf() 方法接受 Object 作为参数而不是 E?

Javascript 动态数组不工作

python - Django 动态模型属性

c - 程序不适用于换行符

c - 在没有现有定义的情况下使用 typedef 是什么意思

python - 使用最大和给定跨度的最佳解析树

r - 从 R 中的列表构建嵌套命名列表

c - C 中的字符数组是动态的吗?