// Example code from "a tutorial on 'dynamic' arrays in C"
// http://fydo.net

// Output:
// Steve's number is 42!
// Bill's number is 33!
// George's number is 15!
// fydo's number is 74!
//
// 6 allocated, 4 used

// This code is public domain. Do whatever you like with it! :D
// I've tested it using GCC, no promises for anything else. Sorry.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
	char *name;
	int number;
} DATA;

DATA 	*TheArray;
int 	numElements = 0; // keep track of the number of elements used
int		numAllocated = 0; // essentially how large the array is

void AddToArray (DATA item)
{
	if(numElements == numAllocated) { // need more refs?
		if (numAllocated == 0)
			numAllocated = 3; // start off with 3 refs
		else
			numAllocated *= 2; // double the refs allocated
			
		TheArray = (DATA*)realloc(TheArray, (numAllocated * sizeof(DATA)));
		
		if (TheArray == NULL)
		{
			fprintf(stdout, "ERROR: Couldn't realloc memory!");
			exit(2);
		}
	}
	
	TheArray[numElements] = item; 
	numElements++;
	
	return;
}

int main()
{
	// Some data that we can play with
	char *names[4] = { "Steve", "Bill", "George", "fydo" };
	int numbers[4] = { 42, 33, 15, 74 };
	int i;
	
	// Populate!
	for (i = 0; i < 4; i++)
	{
		DATA temp;
		
		temp.name = malloc(strlen(names[i]) * sizeof(char));
		temp.name = strdup(names[i]);
		temp.number = numbers[i];
		
		AddToArray(temp);
	}
	
	FILE *out;
	out = fopen( "output.txt", "w" );
	
	// Regurgitate!
	for (i = 0; i < 4; i++)
	{
		fprintf(out, "%s's number is %d!\n", TheArray[i].name, TheArray[i].number);
	}
	
	fprintf(out, "\n%d allocated, %d used\n", numAllocated, numElements);
	
	fclose(out);
	
	// Deallocate!
	for (i = 0; i < 4; i++)
	{
		free(TheArray[i].name);
	}
	free(TheArray);	
	
	// All done
	return 0;
}
