/*
This program manages a list of product prices.
The user can enter a product price and then decide,
whether to continue or to to stop adding new product prices.
After adding product prices, the average price is calculated and printed.

Unfortunately, there are some errors in the code.
The compiler finds a few of them, others are logical
errors and are not detected by the compiler.

This is an example: 

Price for product 1: 6.50
Add another price? (1 = yes, 0 = no): 1
Price for product 2: 2.80
Add another price? (1 = yes, 0 = no): 1
Price for product 3: 9.90
Add another price? (1 = yes, 0 = no): 1
Price for product 4: 450
Add another price? (1 = yes, 0 = no): 0
Average price: 117.30
*/

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

void addPrice(float** prices, int* count, int* capacity)
{
  if (*count >= *capacity)
  {
    *capacity *= 2;
    float *new_prices = realloc(*prices, *capacity * sizeof(float));
    if (new_prices == NULL)
    {
      printf("Memory allocation failed\n");
      return;
    }
    *prices = new_prices;
  }

  printf("Price for product %d: ", *count + 1);
  scanf("%f", &(*prices)[*count]);
}

int main()
{
  int capacity = 2;
  int count = 0;
  float* prices = (float*) calloc(capacity, sizeof(float));
  if (prices == NULL)
  {
    printf("Memory allocation failed\n");
    return 1;
  }

  int additional_price = 0;
  do
  {
    addPrice(&prices, &count, &capacity);
    count++;
    if (prices == NULL)
    {
      return 1;
    }

    printf("Add another price? (1 = yes, 0 = no): ");
    scanf("%d", &additional_price);
  } while (additional_price);

  float total = 0;
  for (int i = 0; i < count; i++)
  {
    total += prices[i];
  }
  printf("Average price: %.2f\n", total / count);

  free(prices);
  return 0;
}