简体   繁体   English

动态分配结构数组

[英]Dynamic allocation of an array of structs

I've found useful answers on other people's questions countless times here on stackoverflow, but this is my first time asking a question of my own. 我已经在stackoverflow上无数次地找到了有关其他人问题的有用答案,但这是我第一次提出自己的问题。

I have a C function that dynamically needs to allocate space for an array of structs and then fill the struct members of each array element with values pulled from a file. 我有一个C函数,它动态地需要为结构数组分配空间,然后用从文件中提取的值填充每个数组元素的结构成员。 The member assignment works fine on the first pass of the loop, but I get a segmentation fault on the second pass. 成员赋值在循环的第一次传递中正常工作,但是在第二次传递时我得到了分段错误。

I've written up this quick program illustrating the essentials of the problem I'm having: 我已经写了这个快速程序,说明了我遇到的问题的基本要点:

#include <stdlib.h>
#include <stdio.h>

typedef struct {
        int a;
        int b;
} myStruct;

void getData(int* count, myStruct** data) {
    *count = 5;
    *data = malloc(*count * sizeof(myStruct));

    int i;
    for (i = 0; i < *count; i++) {
        data[i]->a = i;
        data[i]->b = i * 2;
        printf("%d.a: %d\n", i, data[i]->a);
        printf("%d.b: %d\n", i, data[i]->b);
    }
}

int main() {
    int count;
    myStruct* data;
    getData(&count, &data);
    return 0;
}

The output I get from this is: 我得到的输出是:

0.a: 0
0.b: 0
Segmentation fault

I'm not sure where my problem lies. 我不确定我的问题在哪里。 It seems as though the malloc call is only allocating enough space for one struct when it should be allocating space for five. 似乎malloc调用只为一个struct分配足够的空间,而它应该为5分配空间。

Any help would be very much appreciated. 任何帮助将非常感谢。

The error is here: 错误在这里:

for (i = 0; i < *count; i++) {
    data[i]->a = i;
    data[i]->b = i * 2;
    printf("%d.a: %d\n", i, data[i]->a);
    printf("%d.b: %d\n", i, data[i]->b);
}

you should do this: 你应该做这个:

for (i = 0; i < *count; i++) {
    (*data)[i].a = i;
    (*data)[i].b = i * 2;
    printf("%d.a: %d\n", i, (*data)[i].a);
    printf("%d.b: %d\n", i, (*data)[i].b);
}

The reason is that you are indexing the wrong "dimension" of data . 原因是您正在索引错误的“维度” data

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

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