I have a simple singly linked list, which I'm trying to step through and print the name of the data at each node, in this case the nodes hold fruits which contain a single field, name
:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct store
{
struct list * inventory;
};
struct list
{
struct node * start;
int length;
};
struct node
{
struct fruit * data;
struct node * next;
};
struct fruit
{
char name[20];
};
/* set inventory to default vals */
void store_init(struct store * store)
{
store -> inventory = malloc(sizeof(struct list));
store -> inventory -> start = NULL;
store -> inventory -> length = 0;
}
void open_store(struct store * store)
{
struct node * current;
struct node * traversal_node;
int i;
struct fruit fruits[3];
char * fruit_names[3];
fruit_names[0] = "Apple";
fruit_names[1] = "Mango";
fruit_names[2] = "Orange";
/* populate fruits with relevant data */
for(i=0; i < 3; i++)
{
strcpy(fruits[i].name, fruit_names[i]);
}
for(i=0; i < 3; i++)
{
current = malloc(sizeof(struct node));
current -> data = &fruits[i];
current -> next = NULL;
if(store -> inventory -> start == NULL) { /* check if no other nodes have been inserted, if so, insert at start */
store -> inventory -> start = malloc(sizeof(struct node));
store -> inventory -> start = current;
store -> inventory -> length++;
} else {
traversal_node = store -> inventory -> start; /* start at header */
while(traversal_node->next != NULL) { /* move to end of list */
traversal_node = traversal_node -> next;
}
traversal_node -> next = current; /* add node */
store -> inventory -> length++;
}
}
printf("%s\n", store -> inventory -> start -> data -> name);
}
void print_inventory(struct store * store)
{
printf("%s\n", store -> inventory -> start -> data -> name);
}
int main()
{
struct store store;
/* intiatlize store */
store_init(&store);
open_store(&store);
print_inventory(&store);
}
The first print statement works, but I get nothing when I try calling print_inventory
, and if I try looping through the inventory in that function, I get random characters.
I'll note if I try printf("%s\n", store.inventory -> start -> data -> name);
in main
, it works fine, but I can't seem to pass my store
into the print_inventory
function.
What am I doing wrong?