failure to write a circular list
i have the following code (with some extra bits i haven't programmed yet as the first half isn't working)
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum DAY {MON = 1, TUES, WED, THURS, FRI, SAT, SUN};
enum MONTH {JAN = 1, FEB, MARCH, JUNE, JULY, AUG, SEPT, OCT, NOV, DEC};
typedef struct Days_Node
{
int day_num;
char *weekday;
struct Days_Node *next;
}Days_Node;
typedef struct Months_Node
{
int month_num;
char *month;
struct Months_Node *next;
}Months_Node;
typedef struct Lists
{
struct Days_Node *current_day;
struct Months_Node *current_month;
}Lists;
Days_Node *get_day_memory(void);
Months_Node *get_month_memory(void);
char *get_string_memory(int x);
void add_day_node(Lists *calender);
void add_month_node(Lists *calender);
void free_list(Lists *calender);
int main()
{
int i;
Lists calender;
calender.current_day = NULL;
calender.current_month = NULL;
add_day_node(&calender);
while (calender.current_day->day_num != MON)
{
calender.current_day = calender.current_day->next;
}
for (i = 1; i < 15; i++)
{
printf("day of the week is %s\n", calender.current_day->weekday);
calender.current_day = calender.current_day->next;
if (calender.current_day->next == NULL)
{
printf("not circular\n");
}
}
free_list(&calender);
return 0;
}
Days_Node *get_day_memory(void)
{
return malloc(sizeof(Days_Node));
}
Months_Node *get_month_memory(void)
{
return malloc(sizeof(Months_Node));
}
char *get_string_memory(int x)
{
return (char *)malloc(x + 1);
}
void add_day_node(Lists *calender)
{
int i;
char *days[] = {"", "Monday", "Tuesday", "Wendnesday", "Thursday", "Friday", "Saturday", "Sunday"};
Days_Node *current_tmp = NULL;
for (i = 1; i < 8; i++)
{
Days_Node *tmp_node = get_day_memory();
if (!tmp_node)
{
fprintf(stderr, "unable to allocate memory");
exit(EXIT_FAILURE);
}
calender->current_day = tmp_node;
if (i == 1)
{
current_tmp = tmp_node;
}
tmp_node->day_num = i;
tmp_node->weekday = get_string_memory(strlen(days[i]));
strcpy(tmp_node->weekday, days[i]);
tmp_node->next = NULL;
tmp_node->next = calender->current_day;
calender->current_day = tmp_node;
}
calender->current_day->next = current_tmp;
}
void add_month_node(Lists *calender);
void free_list(Lists *calender)
{
Days_Node *tmp_node = calender->current_day->next;
calender->current_day->next = NULL;
calender->current_day = tmp_node;
while(calender->current_day->next)
{
tmp_node = calender->current_day->next;
free(calender->current_day->weekday);
free(calender->current_day);
calender->current_day = tmp_node;
printf("freed memory\n");
}
}
im sure im doing something screwy with linking the head node to the tail node (current_tmp) but cant for the life of me figure out how else to do it.
coop