Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > Realloc a struct **

Reply
Thread Tools

Realloc a struct **

 
 
Henrik J
Guest
Posts: n/a
 
      11-10-2003
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(F OO*));
foo=tempfoo;

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

Regards Henrik Tomra
 
Reply With Quote
 
 
 
 
David White
Guest
Posts: n/a
 
      11-10-2003
"Henrik J" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed) om...
> 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(F OO*));
> 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



 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Can *common* struct-members of 2 different struct-types, that are thesame for the first common members, be accessed via pointer cast to either struct-type? John Reye C Programming 28 05-08-2012 12:24 AM
Typedef A references struct B which references struct A which... DanielEKFA C++ 8 05-16-2005 10:26 AM
struct in struct Gunnar G C++ 14 06-02-2004 06:43 PM
struct my_struct *p = (struct my_struct *)malloc(sizeof(struct my_struct)); Chris Fogelklou C Programming 36 04-20-2004 08:27 AM
implementing a templated struct within a templated struct RA Scheltema C++ 3 01-06-2004 11:25 AM



Advertisments