简体   繁体   English

结构体动态数组的初始化

[英]Initialization of dynamic array of structs

This is my struct:这是我的结构:

typedef struct ElementToInsert {
    char *key;
    char *value;
} element;

This is my function:这是我的功能:

void init_hash(int size, element**arr) {
    *arr = malloc(size * sizeof(element*));
    if (arr == NULL)
    {
        printf("Out of memory\n");
        return 0;
    }
    for (int i = 0; i < size; i++) {

        (*arr)[i].key = NULL;
        (*arr)[i].value = NULL;
    }

}

And the main() :main()

void main() {
    element *hash_table = NULL;
    int hash_table_size = 10;
    init_hash(hash_table_size, &hash_table);
}

The problem is that when I run the debugger (in visual studio 2015) it doesn't show me all the array values.问题是,当我运行调试器(在 Visual Studio 2015 中)时,它没有显示所有数组值。 I expect to see something like: hash_table[0] = {key = NULL, value = NULL}, hash_table[1] = {key = NULL, value = NULL} but all I see is this:我希望看到类似的东西: hash_table[0] = {key = NULL, value = NULL}, hash_table[1] = {key = NULL, value = NULL}但我看到的是:

在此处输入图片说明

Passing a double pointer to init_hash is unnecessarily complicated.将双指针传递给init_hash是不必要的复杂。 While there are plenty of valid uses for double pointers, this isn't one of them.虽然双指针有很多有效的用途,但这不是其中之一。 Normally double pointers are used for multiple output variables or to swap out existing memory, but since you have no return value and you're allocating the memory anyway, it just invites errors.通常双指针用于多个输出变量或换出现有内存,但由于您没有返回值并且无论如何您都在分配内存,它只会引发错误。 Keep things simple and return a pointer to your list of elements.保持简单并返回指向元素列表的指针。

element *init_hash(size_t size) {
    element *hash = calloc(size, sizeof(element));

    if (hash == NULL) {
        fprintf(stderr, "Out of memory\n");
        exit(1);
    }

    return hash;
}

A few things of note.一些注意事项。 First is that to allocate an array of structures, you allocate size * sizeof(element) .首先是分配一个结构数组,你分配size * sizeof(element) That allocates memory for size structs.这为size结构分配内存。 If you use size * sizeof(element*) that allocates memory for size pointers to the struct .如果您使用size * sizeof(element*)指向 struct 的size指针分配内存。 Both are valid, but you have to choose which one you're working with.两者都是有效的,但您必须选择要使用的那个。 You appear to be working with a list of structs.您似乎正在使用结构列表。

Unlike malloc , calloc will zero the memory for you.malloc不同, calloc将为您清零内存。 This avoids the need to manually zero each struct saving some code and time.这避免了手动将每个结构归零的需要,从而节省了一些代码和时间。

If you run out of memory, and you don't have a plan to deal with it, it's probably best to just save yourself a whole lot of subsequent error messages and exit .如果您的内存不足,并且您没有计划来处理它,那么最好只为自己保存大量后续错误消息并exit

Finally, sizes are best stored as size_t .最后,尺寸最好存储为size_t It's the type that C uses for array sizes and it can catch some type issues.这是 C 用于数组大小的类型,它可以捕获一些类型问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM