CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Aug 2001
    Posts
    60

    resizing an array

    I suppose I have an array

    mystruct* tab[..]

    but how can I dynamicly add elements into it ?

    I want to have a function like

    addElement(myStruct *element)
    {
    then add *element to my array
    }

    I just want a hint about how I could do this

    thanks

  2. #2
    Join Date
    Apr 1999
    Posts
    27,449

    Re: resizing an array

    Originally posted by trasher
    I suppose I have an array

    mystruct* tab[..]

    but how can I dynamicly add elements into it ?
    If this is C++ and not 'C', use std::vector instead an array. There is no such thing as a dynamic array, since arrays in C++ are always fixed. So you either must use pointers with new and delete, or preferably, just create a vector of your items.
    I want to have a function like

    addElement(myStruct *element)
    {
    then add *element to my array
    }

    I just want a hint about how I could do this

    thanks
    Using vector:
    Code:
    #include <vector>
    typedef std::vector<myStruct> MyStructArray;
    
    MyStructArray MArray;;
    
    void addElement(myStruct& m)
    {
         MArray.push_back( m );
    }
    You can now use MArray just like an array, including using operator [] to access and set elements.

    Regards,

    Paul McKenzie

  3. #3
    Join Date
    May 2000
    Location
    Phoenix, AZ [USA]
    Posts
    1,347
    You can't add elements to a statically-bound array. You'd either
    have to create your own array with malloc() or new[]. Hopefully,
    you're using C++; if so, you can use std::vector instead of using
    a statically-bound array:
    Code:
    std::vector<mystruct*> v;
    v.push_back(pStruct);
    --Paul

    Edit: I'm sorry, Paul McKenzie; I guess we posted at very similar
    times

  4. #4
    Join Date
    Aug 2001
    Posts
    60
    thanks!

    I will look for std::vector...

    When I was doing C, it was so painfull to use malloc and realloc

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured