Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <glib.h>
- typedef struct
- {
- int item_id;
- unsigned char *item_name;
- double item_price;
- int item_stock_count;
- } item_data;
- void print_item(item_data *item_ptr)
- {
- printf("item_id: %i,\n item_name: %s,\n item_price: %g,\n item_stock: %i\n",
- item_ptr->item_id,
- item_ptr->item_name,
- item_ptr->item_price,
- item_ptr->item_stock_count);
- }
- int main()
- {
- GSList *items_list1 = NULL, *iterator = NULL;
- item_data *tmp_item = NULL;
- int i = 0;
- char *tmp_str = NULL, *tmp_str2 = NULL;
- tmp_str = malloc(1);
- for(i = 0; i < 3; i++)
- {
- sprintf(tmp_str, "%d", i);
- tmp_str2 = (unsigned char *)malloc(100);
- if (tmp_str2 == NULL)
- {
- fprintf(stderr, "Couldn't allocate memory\n");
- return -1;
- }
- strcpy(tmp_str2, "item_num num: ");
- strcat(tmp_str2, tmp_str);
- // ***Allocate memory using glib***
- tmp_item = g_new(item_data, 1);
- if (tmp_item == NULL)
- {
- fprintf(stderr, "Couldn't allocate memory\n");
- return -1;
- }
- tmp_item->item_id = i;
- tmp_item->item_name = tmp_str2;
- tmp_item->item_price = 100*(i+1);
- tmp_item->item_stock_count = 10*(i+1);
- items_list1 = g_slist_append(items_list1, tmp_item);
- }
- // Clean up
- for(iterator = items_list1; iterator != NULL; iterator=iterator->next)
- {
- free(((item_data*)iterator->data)->item_name);
- g_free(iterator->data);
- }
- for(iterator = items_list1; iterator != NULL; iterator=iterator->next)
- print_item((item_data*)iterator->data);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement