KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I am creating a linked list as in the previous question I asked. I have found that the best way to develop the linked list is to have the head and tail in another structure. My products struct will be nested inside this structure. And I should be passing the list to the function for adding and deleting. I find this concept confusing. I have implemented the initialize, add, and clean_up. However, I am not sure that I have done that correctly. When I add a product to the list I declare some memory using calloc. But I am thinking shouldn't I be declaring the memory for the product instead. I am really confused about this adding. Many thanks for any suggestions, #include <stdio.h> #include <stdlib.h> #include <string.h> #define PRODUCT_NAME_LEN 128 typedef struct product_data { int product_code; char product_name[PRODUCT_NAME_LEN]; int product_cost; struct product_data_t *next; }product_data_t; typedef struct list { product_data_t *head; product_data_t *tail; }list_t; void add(list_t *list, int code, char name[], int cost); void initialize(list_t *list); void clean_up(list_t *list); int main(void) { list_t *list = NULL; initialize(list); add(list, 10, "Dell Inspiron", 1500); clean_up(list); getchar(); return 0; } void add(list_t *list, int code, char name[], int cost) { // Allocate memory for the new product list = calloc(1, sizeof(list_t)); if(!list) { fprintf(stderr, "Cannot allocated memory"); exit(1); } if(list) { // First item to add to the list list->head->product_code = code; list->head->product_cost = cost; strncpy(list->head->product_name, name, sizeof(list->head->product_name)); // Terminate the string list->head->product_name[127] = '/0';
Tags (comma-separated)
Save Edits
Cancel