structure dynamic memory allocation?
I have an assignment that's basis is about dynamic memory allocation. I'm given two files. One is a file with the list of months from January-December. I have to allocate space to store all of these. I did that.
The second file has a bunch of dates such as January 17, 2004. I have to store/update a count for each month and year it is in. I wanted to go about this by doing using structures. I read linked lists would be good for this but we don't learn that until next week. Anyways one of the requirements is...
"The memory for storing the counts should by dynamicallyallocated"
So if I do use structures I have to dynamically allocate the memory.
Here's what I have so far. I commented out the struct dates because it wasn't working. But that's to try to help show along the lines of what I'm thinking if this makes sense.
Thanks for any help.
Code:
struct dates
{
char months[20];
int years;
};
int main(void)
{
FILE *fp;
char buffer[50];
char **month_and_year = NULL;
char **list_of_months = NULL;
int counter1 = 0;
int counter2 = 0;
int line_len;
char *month;
char *year;
char *del = ",";
//Opens the first file and stores the months individually in list_of_months
if ( (fp = fopen("months.txt", "r" )) == NULL )
{
printf("Couldn't open file\n");
exit(1);
}
while(fgets(buffer, sizeof(buffer), fp))
{
list_of_months = realloc(list_of_months, (counter1+1) *sizeof(char*) );
line_len = strlen(buffer);
list_of_months[counter1] = calloc(line_len+1, sizeof(char));
strcpy(list_of_months[counter1],buffer);
counter1++;
}
fclose( fp );
//Opens the second file and stores the month in month and year in year.
if ( (fp = fopen("dates.csv", "r" )) == NULL )
{
printf("Couldn't open file\n");
exit(1);
}
while(fgets(buffer, sizeof(buffer), fp))
{
month_and_year = realloc(month_and_year, (counter2+1) *sizeof(char*) );
line_len = strlen(buffer);
month_and_year[counter2] = calloc(line_len+1, sizeof(char));
strcpy(month_and_year[counter2],buffer);
month = strtok (month_and_year[counter2], del);
year = strtok (NULL, del);
//struct dates *array = realloc( array, (counter2+1)*sizeof(char*));
counter2++;
}
fclose( fp );
free(list_of_months);
free(month_and_year);
getchar();
return 0;
}