Help with dynamic arrays

Started by
14 comments, last by slyterence 22 years, 8 months ago
Pseudo: Are you sure about that ? This is more the working of the realloc() function. And it''s quite dangerous to use, if you want to avoid using double referenced pointers.

Eg.

int *a;
int *b;

a = realloc(NULL, 1024); // initial allocation
*a = 5;
b = a;

a = realloc(a, 2048); // We need more

printf("%d\n", *b);

We would expect a ''5'' here, but the result is likely to be a crash, since the memory may have been moved somewhere else and is invalid. That means, that you cannot keep _any_ pointers to this kind of memory, or you have to use things like **b=5 and update *b to the new pointer location. Confusing.

-AH

Advertisement
Damn, how can you represent square brackets on this message board without triggering some kind of bizarre font effect ?

-AH
Pseudo Thanks for the info but,

Are you sure, it seems to me that copying over the data would be a woeful waste of time and not to mention recourses. Granted I would expect that there would be over allocation each time the memory is allocated so that you are not copying over at each pushback (or whatever it is). After my last post I was thinking of ways to implement a vector type memory allocation method my self. It would need to be fast so I would like to shy away from linked lists as much as possible sequential array’s are faster (I am quite sure on that one). Anyway would not a linked list of arrays be fast than a vector (this would be overall performance of course). Any thoughts welcome.


Anon,



Why don''t you just make two passes through the data? It is the best way to tackle this situation.
Use STL''s vector class. Using this class all memory management is done for you and all you have to do is add new elements to the end of the vector, You only need to make one pass thru the data too.

typedef struct
{
float x, y, z
} Vertex;

std::vector< Vertex > list;

// Read 3DS vertex data from file
Read3DSVertex( &vertex );

list.push_back( vertex );

---
Visit Particle Stream Studios - Home of Europa, Tachyon and winSkin
---Visit InterfaceFX - Home of Europa, Tachyon and winSkin
Hi

I think I am just a stickler for speed, I hate doing two passes through data it just seems so wasteful and I am also starting to dislike linked lists (large ones at least). Vectors sounded so cool until Pseudo said that all the data in the array is copied over, I can think of many occasions were a task like that would be undesirable. I will do some performance tests on arrays, linked lists, vectors and linked lists of arrays for different situations.


Anon,

This topic is closed to new replies.

Advertisement