I am having a go at making my own managed double list function. However, I have a problem, it seems as if the the values in the array vanish when the value of one of the member items in the struct is printed. I am not sure what is causing it (probably some stupid mistake due to my sloppy coding). It does compile fine with gcc -Wall.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//#include <math.h>
struct doubleList
{
int size;
int realSize;
int incr;
double *list;
};
struct doubleList* initList (int baseSize, int incr)
{
struct doubleList list, *lp;
lp = &list;
lp->size = baseSize;
lp->realSize = 0;
lp->incr = incr;
lp->list = malloc(sizeof(double) * baseSize);
return lp;
}
int addDoubleList (struct doubleList* lp, double item)
{
if (lp->size == lp->realSize)
{
realloc(lp->list, sizeof(double) * (lp->size + lp->incr));
lp->size += lp->incr;
}
lp->list[lp->realSize] = item;
lp->realSize++;
return lp->realSize;
}
int main (int argc, char *argv[])
{
struct doubleList *list = initList(1, 2);
addDoubleList(list, 3.1415926535);
addDoubleList(list, 2.71828183);
printf("Item One is: %.8f, Item Two is: %.8f\n", list->list[0], list->list[1]);
printf("Size is: %i, Real Size is: %i\n", list->size, list->realSize);
printf("Item One is: %.8f, Item Two is: %.8f\n", list->list[0], list->list[1]);
exit(EXIT_SUCCESS);
return 0;
}
When run it prints:
Item One is: 3.14159265, Item Two is: 2.71828183
Size is: 3, Real Size is: 2
Item One is: 0.00000000, Item Two is: 0.00000000
I am not sure what causes it but printing out the size causes the values to vanish!
Can anyone help me?