结构体数组的动态分配
我在 stackoverflow 上无数次找到了其他人问题的有用答案,但这是我第一次提出自己的问题。
我有一个 C 函数,它动态地需要为结构数组分配空间,然后用从文件中提取的值填充每个数组元素的结构成员。成员分配在循环的第一遍中工作正常,但在第二遍中出现分段错误。
我编写了这个快速程序,说明了我遇到的问题的本质:
#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;
}
我从中得到的输出是:
0.a: 0
0.b: 0
Segmentation fault
我不确定我的问题出在哪里。看起来 malloc 调用只为一个结构分配足够的空间,而它应该为五个结构分配空间。
任何帮助将非常感激。
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.
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. 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.
Any help would be very much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
错误在这里:
你应该这样做:
原因是你正在索引
数据
的错误“维度”。The error is here:
you should do this:
The reason is that you are indexing the wrong "dimension" of
data
.