Realloc a struct **

Discussion in 'C++' started by Henrik J, Nov 10, 2003.

  1. Henrik J

    Henrik J Guest

    Hello group...
    I have this little problem:

    I'm using a struct **foo. I have allocated x foo's using malloc:

    foo=(FOO**)malloc(Amount*sizeof(FOO*));

    No problem....!


    but my question is now: How do I realloc a **foo...!
    I'm thinking of doing:

    struct **tempfoo;
    tempfoo=(FOO**)realloc(Amount+extraAmount,sizeof(FOO*));
    foo=tempfoo;

    Somehow this will not work...
    Hope some of you can help...

    Regards Henrik Tomra
    Henrik J, Nov 10, 2003
    #1
    1. Advertising

  2. Henrik J

    David White Guest

    "Henrik J" <> wrote in message
    news:...
    > Hello group...
    > I have this little problem:
    >
    > I'm using a struct **foo. I have allocated x foo's using malloc:


    You mean x FOOs, right?

    >
    > foo=(FOO**)malloc(Amount*sizeof(FOO*));
    >
    > No problem....!
    >
    >
    > but my question is now: How do I realloc a **foo...!
    > I'm thinking of doing:
    >
    > struct **tempfoo;
    > tempfoo=(FOO**)realloc(Amount+extraAmount,sizeof(FOO*));
    > foo=tempfoo;
    >
    > Somehow this will not work...


    Well, the documentation I have declares 'realloc' as:
    void *realloc( void *memblock, size_t size );

    So the correct code would be:
    foo = static_cast<FOO**>(realloc(foo, new_size_in_bytes));

    However, it almost offends the senses to see static_cast and realloc in the
    same statement, so maybe it's better to make it:
    foo = (FOO**)realloc(foo, new_size_in_bytes);

    At least then you can move the code to a C source file where it belongs.

    > Hope some of you can help...


    The best help I can offer is to repeat the following line 1000 times:
    "When writing C++ code I will never use 'malloc' again."

    Unless you have special reasons for writing C code in C++, use a std::vector
    to store your pointers. It does all reallocations for you.

    DW
    David White, Nov 10, 2003
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. RA Scheltema
    Replies:
    3
    Views:
    383
    RA Scheltema
    Jan 6, 2004
  2. Gunnar G

    struct in struct

    Gunnar G, May 31, 2004, in forum: C++
    Replies:
    14
    Views:
    790
  3. DanielEKFA
    Replies:
    8
    Views:
    593
    DanielEKFA
    May 16, 2005
  4. James Harris
    Replies:
    4
    Views:
    1,363
    James Harris
    Oct 9, 2003
  5. Chris Fogelklou
    Replies:
    36
    Views:
    1,358
    Chris Fogelklou
    Apr 20, 2004
Loading...

Share This Page