Advertisement

Large Arrays in C++

Started by December 12, 2000 05:01 PM
3 comments, last by DisKordCoder 24 years, 1 month ago
Ive come across a problem. Im holding Vertex data in an Array, like: struct Vector { float X; float Y; float Z; } struct Object { Vector Vertex[100]; } Problem is that the Array (which is seen as 100 above) will not go as high as i need (about 10000). Is there a better way to set up large Arrays? Is there another technique?
You can try dynamically allocating the memory, or multidimensional arrays. Vector[100][100] or, you can create a constructor for the Vector class which dynamically allocates the memory when it is created.

-----------------------------

A wise man once said "A person with half a clue is more dangerous than a person with or without one."

The Micro$haft BSOD T-Shirt
-----------------------------A wise man once said "A person with half a clue is more dangerous than a person with or without one."The Micro$haft BSOD T-Shirt
Advertisement
In C++, declare the array instead as a pointer, e.g:

Vector *pVector; // member of Object

and in your constructor for Object, include:

#define NUM_VECTORS 10000
pVector = new Vector[NUM_VECTORS];

You can then use this pointer as an array of size NUM_VECTORS. You'll need to do:

delete[] pVector;

in the destructor for Object.

Dave

Edited by - Heraldin on December 12, 2000 6:11:13 PM
Well, take a look at what actually happens when you try to create a new array like this:

Vector Vertex[10000];

The compiler tries to create the entire array on the stack... That would be 120000 bytes, which is BIG... That much memory should be allocated on the heap, rather than on the stack.

And do that with dynamic memory allocation... If you''re using C++, you can use the method suggested by Heraldin. If you''re using straight C, as your code would suggest, you can do something like this:

Vector *Vertex = malloc(10000 * sizeof(Vector));

A single call to

free(Vertex);

will free the memory.

And as Heraldin said, this gives you a pointer that you can access the same way as an array. Vertex[0] still gives you the first element.
If your using C++, try using an STL vector class. It provides a dynamic array container that grows as needed. It would be much less memory intensive.

Anon

This topic is closed to new replies.

Advertisement