Realloc a struct **

H

Henrik J

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
 
D

David White

Henrik J said:
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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top