Reputation: 21
I created array of structs and I created them in the function config_course_list
with a file that contains courses information.
I tested variables at the of the function and it is correct. However when I call this function in main
, the *courses
has size 1, contains only one struct. Which I can print courses[0].code
and courses[0].description
, but fail to print courses[1].code
and description
.
What should I do to make it work?
config_course_list:
int config_course_list(Course **courselist_ptr, char *config_filename) {
FILE *f;
char buff[INPUT_BUFFER_SIZE];
f = fopen(config_filename, "r");
if (f == NULL)
{
perror("file");
}
fgets(buff,INPUT_BUFFER_SIZE+1,f);
int size = atoi(buff);
*courselist_ptr = (Course *)malloc(size * sizeof(Course));
for (int i = 0; i < size; ++i)
{
courselist_ptr[i] = malloc(sizeof(Course));
}
int index = 0;
char *token[size];
for (int i = 0; i < size; ++i)
{
token[i] = malloc(sizeof(char)*INPUT_BUFFER_SIZE);
}
while (fgets(buff,INPUT_BUFFER_SIZE+1, f) != NULL)
{
strcpy(courselist_ptr[index]->code, strtok(buff, " "));
strcpy(token[index],strtok(NULL, "\n"));
courselist_ptr[index]->description=token[index];
index ++;
}
return size;
}
main:
Course *courses;
int num_courses = config_course_list(&courses, argv[1]);
printf("%s\n", courses[1].code);
struct course:
struct course{
char code[7];
char *description;
};
Upvotes: 2
Views: 101
Reputation: 20969
Delete these lines:
for (int i = 0; i < size; ++i)
{
courselist_ptr[i] = malloc(sizeof(Course));
}
what is the purpose of above loop ? It looks like you want to create 2D array ... not this way.
Your aim is to create 1D array and you do it by
*courselist_ptr = (Course *)malloc(size * sizeof(Course));
and it is enough, the array was created now you can fill it by some data.
When you created 1D array,
and p
points to the first element of this array you have two ways
to access i-th element:
p[i]
or
*(p + i)
^ - p is pointer to first element of array
In your case p
is *courselist_ptr
so if you want to read/write code
member you can use:
(*courselist_ptr)[i].code
(*courselist_ptr + i)->code
(*(*courselist_ptr + i)).code
so you have to replace
courselist_ptr[index]->code
by (*courselist_ptr)[index].code
and courselist_ptr[index]->description
by (*courselist_ptr)[index].description
.
Upvotes: 2