Thread: Vanishing Doubles

  1. #1
    Registered User
    Join Date
    Apr 2005

    Vanishing Doubles

    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.
    #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;
    	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]);
    	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?

  2. #2
    Registered User
    Join Date
    Aug 2005
    function initList() returns a pointer to an object allocated on the stack. Consequently when the function returns that object goes out of scope and is no longer valid. You should consider either making object named list a static object or passing it in as a parameter.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. problem w/ doubles in friend's program
    By mkylman in forum C Programming
    Replies: 16
    Last Post: 11-22-2008, 10:45 AM
  2. parse doubles from socket read?
    By willy in forum C Programming
    Replies: 4
    Last Post: 05-28-2008, 05:32 AM
  3. sscanf with doubles
    By ufsargas in forum C Programming
    Replies: 1
    Last Post: 06-28-2006, 03:05 PM
  4. Passing array of doubles to ATL COM dll
    By wakeup in forum C++ Programming
    Replies: 3
    Last Post: 04-11-2006, 02:53 AM
  5. ints and doubles problem
    By iLLiCiT in forum C Programming
    Replies: 1
    Last Post: 12-04-2004, 03:42 PM