View Full Version : arrays (OT)

01-08-2001, 10:00 PM
sorry about this OT subject but i desperatly need help!! http://www.opengl.org/discussion_boards/ubb/smile.gif

Basically I need to create and array of n elements of 3. say Array[n][3].

any ideas??

01-09-2001, 04:45 AM
Yes, do it as a one dimensional array.

float *myArray;
myArray = new float[n*3];

And then access the array like this.

// extraxt 2:nd element in the 8:th element
float myVal = myArray[7*3+1];

7 is for 8:th element
3 is for three posts per element
1 is for second post in the element

01-09-2001, 12:18 PM
thats great thanks, ill give it a try!

Does anyone know the reason why you cannot use variables in arrays in C++?? eg array[number]??

01-09-2001, 12:38 PM
An ordinary explicit array in C can not use a varible size in the declaration. Thats just how they work. The compiler needs to know at compile-time how much memory the array will use so that it can create the code that reserves the space for it at runtime. If you need an array with a variable size, then what you do is dynamically allocate space for it. You can then treat the resulting pointer as an array, since that's what an array variable is anyway. You just have to remember to deallocate the memory when you are finished with the array. Or better yet, just use the vector template class in the STL. These can function as arrays that can grow arbitrarily.

01-09-2001, 01:57 PM
I've used this crazy solution:

typedef float[3] myThreeFloats;

myThreeFloats* pMyFloats = new myThreeFlaots[n];

Then you can access pMyFloats[i][0..1..2].

I dont necessarily recommend doing it this way though http://www.opengl.org/discussion_boards/ubb/smile.gif I used it for a very specific case. (A variable length array of fixed sized strings).

01-10-2001, 02:01 PM
JUst trying your idea now BwB - but in visual c++ 6 I get this error

warning C4091: 'typedef ' : ignored on left of 'float' when no variable is declared

Im just trying to figure this out so ill get back soon.

01-10-2001, 03:13 PM
There is a bug in BwB's example. I believe he meant to type:
typedef float myThreeFloats[3];