Dynamic array classing problem

This is a discussion on Dynamic array classing problem within the C++ Programming forums, part of the General Programming Boards category; The following has some memory allocation error. When I try to add the first entry it has no prob, but ...

  1. #1
    Registered User Zeeshan's Avatar
    Join Date
    Oct 2001
    Location
    Munich, Germany
    Posts
    224

    Dynamic array classing problem

    The following has some memory allocation error. When I try to add the first entry it has no prob, but on further additions some of the element cannot be accessed (are not saved with their actual values...)

    template <class T>
    class List
    {
    public:
    List(); // <-- Constructor
    int add(T rec);
    ~List();

    T *data;
    int n;
    };

    template<class T>
    int List<T>::add(T rec)
    {
    if (n==0) {
    data = (T*) malloc(sizeof(T));
    if (data==NULL) return FALSE;
    n=1;
    data[n-1] = rec;
    }
    else {
    data = (T*) realloc(data,sizeof(T)*n+1);
    if (data==NULL) return FALSE;
    n++;
    data[n-1] = rec;
    }
    return TRUE;
    }

    template<class T>
    List<T>::List()
    {
    n=0;
    }

    template<class T>
    List<T>::~List()
    {
    if (n!=0) free((void*)data);
    }

  2. #2
    zen
    zen is offline
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    You have a precedence problem -

    data = (T*) realloc(data,sizeof(T)*n+1);

    should be

    data = (T*) realloc(data,sizeof(T)*(n+1));

    Also, this isn't really a list, it's just a dynamically sized array.
    zen

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    42
    Wouldn't you be better off using the template stucture correctly


    Code:
    typedef List<int> ListStack;
    
    ListStack LS;

    Marky_Mark

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. problem copy from array to another
    By s-men in forum C Programming
    Replies: 3
    Last Post: 09-07-2007, 02:51 PM
  2. A question related to strcmp
    By meili100 in forum C++ Programming
    Replies: 6
    Last Post: 07-07-2007, 03:51 PM
  3. Dynamic array problem
    By new here in forum C++ Programming
    Replies: 9
    Last Post: 03-12-2003, 06:39 PM
  4. Dynamic Array Problem
    By adc85 in forum C++ Programming
    Replies: 2
    Last Post: 03-04-2003, 02:29 PM
  5. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 09:31 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21