C - Create function to build a struct based linked list

Description

Create function to build a struct based linked list

Demo

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

#define ITEMS 5 //from  ww w .j  a  v a2s . co m

struct Product {
  char symbol[5];
  int quantity;
  float price;
  struct Product *next;
};
struct Product *first;
struct Product *current;
struct Product *newCurrent;

struct Product *make_structure(void);
void fill_structure(struct Product *a, int c);
void show_structure(struct Product *a);

int main()
{
  int x;

  for (x = 0; x<ITEMS; x++)
  {
    if (x == 0)
    {
      first = make_structure();
      current = first;
    }
    else
    {
      newCurrent = make_structure();
      current->next = newCurrent;
      current = newCurrent;
    }
    fill_structure(current, x + 1);
  }
  current->next = NULL;

  /* Display database */
  puts("Investment Portfolio");
  printf("Symbol\tShares\tPrice\tValue\n");
  current = first;
  while (current)
  {
    show_structure(current);
    current = current->next;
  }

  return(0);
}

struct Product *make_structure(void)
{
  struct Product *a;

  a = (struct Product *)malloc(sizeof(struct Product));
  if (a == NULL)
  {
    puts("Some kind of malloc() error");
    exit(1);
  }
  return(a);
}

void fill_structure(struct Product *a, int c)
{
  printf("Item #%d/%d:\n", c, ITEMS);
  printf("Stock Symbol: ");
  scanf("%s", a->symbol);
  printf("Number of shares: ");
  scanf("%d", &a->quantity);
  printf("Share price: ");
  scanf("%f", &a->price);
}

void show_structure(struct Product *a)
{
  printf("%-6s\t%5d\t%.2f\t%.2f\n", \
    a->symbol,
    a->quantity,
    a->price,
    a->quantity*a->price);
}

Result

Related Topic