I need to pass an array of structs to a function and it is my understanding that I have to allocate memory for the whole array of structs, as well as for each individual struct member in every struct inside the array.
The way I have done it results in an invalid write error from valgrind (caused in the second line inside function read_file). What is wrong?
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: I know that I have to free the allocated memory, but first I want to get the above code working.