c - 如何将数据存储在动态结构数组中?

标签 c arrays struct dynamic-allocation

我有这些结构,我想用它们来实现 map

typedef struct {
    const char *name;
    int number;
}   Entry;

typedef struct {
    int available;
    int guard;
    Entry *entries;
} Map;

以及用于初始化并将元素放入其中的代码:

Map *map_init() {
    Map *res = (Map *) malloc(sizeof(Map));

    res->available = 4;
    res->guard = 0;
    res->entries = (Entry *) malloc(4 * sizeof(Entry));

    return res;
}

int map_put(Map *map, const char *name, int nr) {
    Entry entry;
    int i = 0;

    for (i = 0; i < map->guard; ++i) {
        entry = map->entries[i];
        printf("entry (  x , %u) at %p (%p)\n", entry.number, &entry, entry.name);

        if (!strcmp(entry.name, name))        // Segmentation fault here
            return 0;
    }

    entry = map->entries[map->guard++];
    entry.name = name;
    entry.number = nr;

    printf("entry (%s, %u) at %p (%p)\n", entry.name, entry.number, &entry, entry.name);

    return 1;
}

当我运行我的主要方法时

int main(int argc, char **argv) {
    printf("Initialising...\n");
    Map *map = map_init();

    printf("Putting...\n");
    map_put(map, "test", 2);
    map_put(map, "some", 1);

    // ...

    free(map->entries);
    free(map);
    return 0;
}

我得到输出

Initialising...
Putting...
entry (test, 2) at 0x7fff50b32a90 (0x10f0cdf77)
entry (  x , 0) at 0x7fff50b32a90 (0x5000000000000000)
Segmentation fault: 11

从中我可以得出段错误是由于 entry.name 不再指向字符串(数字也丢失了,但这不会导致未经授权的内存)使用权)。在第一次调用 map_put 中设置数据后,所有内容似乎都存储在正确的位置。

有人知道这些条目可以在哪里被覆盖或者为什么不存储这些值吗?

最佳答案

问题是这样的:

entry = map->entries[map->guard++];

在这里,您将数组中的数据复制entry结构实例中。然后修改 entry 的数据并放弃这些修改。数组中的(原始)结构数据仍然未修改。

当您在下一次调用 map_put 时使用数组中未初始化的结构时,这当然会导致未定义的行为

要么直接修改数组结构实例,单独增加map->guard。或者将 entry 设为指针并使其指向数组元素。

关于c - 如何将数据存储在动态结构数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41714124/

相关文章:

python distutils,用生成的源代码编写c扩展

c - F.3 操作,9 列出 5 个 FE_ 宏,后跟 4 个 IEEE 754 舍入方向属性,以 "respectively": mistake? 结尾

c++ - 检测文件描述符何时来自/proc

c++ - 基于字符串对结构数组进行排序

c - 使用全局结构变量时出现段错误

c - C 中的“类”行为

c - realloc,动态内存分配

javascript - 将 html 更改为数组中的下一项 - jquery

jquery如何填充数组

c - 并行更新包含 1000000 个项目的数组