【发布时间】:2019-03-05 11:02:37
【问题描述】:
我需要将一个结构数组传递给一个函数,我的理解是我必须为整个结构数组以及数组内每个结构中的每个单独的结构成员分配内存。
我这样做的方式导致来自 valgrind 的无效写入错误(在函数 read_file 内的第二行引起)。怎么了?
typedef struct test
{
char *string1;
int num1;
int num2;
char *string2;
} Test;
static void read_file(Test *test)
{
test = (Test *)calloc(16, sizeof(test));
test[0].string1 = (char *)calloc(strlen("hello") + 1, sizeof(char));
}
int main(void)
{
int i = 0;
Test test[16];
for (i = 0; i < 16; i++)
{
memset(&test[i], 0, sizeof(test[i]));
test[i] = (Test) { "", 0, 0, "" };
}
read_file(test);
return 0;
}
PS:我知道我必须释放分配的内存,但首先我想让上面的代码工作。
【问题讨论】:
-
不要忘记参数是按值传递的,即它们是复制的。副本的修改(即对局部参数变量的赋值)不会改变原始的。当您在
read_file函数中对test进行赋值时,请考虑这一点。 -
另外,
test已经指向(第一个元素)一个现有数组,为什么还要分配新内存?
标签: c struct dynamic-memory-allocation calloc