Array allocation

Hi,

I'm pretty new to C++ (as you'll see from my question). I have experience in other languages, but that might actually be hindering me at the minute.

Ok, first of all, i read in a number from a binary file. This number (in this case) happens to be 200. This is stored in the variable nx.

That bit is fine. However, i want to then create a float array, which has the 200 elements.

Previously, i would have done something like:

float x[nx];

but this does not work. If i input the number explicitly, then it does:

float x[200];

Therefore, i was wondering how i can go about doing this, if at all possible?
Hope this makes sense......
The array size must be a constant, which is why 200 works.
Use a std::vector, you create it like this:
std::vector<float> x ( nx ); ( vector of floats called 'x' containing 'nx' elements )
Then you can use it as an array, but it has the advantages of being re-sizable and managing memory itself
You could set up a pointer and assign it memory:

1
2
3
4
5
6
7
8
9
float *x;

// get nx

x = new float[nx];

// and after you are done with it
delete [] x;
x = 0; // -- edit: added this 


It's better to use something like a vector though:

1
2
3
4
5
6

#include <vector>


std::vector<float> x;
Last edited on
craniumonempty:

I'm glad i found this topic. What if i want to create a two-dimensional array? It does not work:

int * array = new int[2][number];

The same shit: "must be a constant value", but just with Y (number), the X (2) seems to be good. The "number" is a pre-defined value, i have to use it. It works with one-dimensional array, but not with two-dimensional. I know how to use vectors, but it's a little part of a function and also want to learn how to do with this.

It works:

int * array = new int[number];

Last edited on
thanks guys, that worked a treat: using the vector method. :)
Topic archived. No new replies allowed.