Initializing and Array with a Variable

Im having an issue with initializing an array using a variable (as opposed to just a number). Here's an example of the code:

1
2
3
4
5
6
7
8
int Data = 25;          //--- lets say I have 25 data points (read from a file)
                        //--- and I wanna put these datapoints into an array
double DataArray[Data]; //--- so I initialize a 25-cell array

for(i=0;i<=Data;i++)    //--- then fill it with values
{
  DataArray[i] = /*corresponding data point*/;
}


..but when I do this I get the following error from the compiler: " 'Data' - integer number expected "

but if I initialize it as "double DataArray[25];" it works as expected.

How can this be.. "Data" IS "25" ..it IS an integer.

The reason I need to initialize this way is because the number of datapoints, and thus the integer "Data" would change with each run so I would need the program to create the array sized accordingly.

I tried initializing the array as empty and storing values into it hoping it would grow accordingly:

1
2
3
4
5
6
double DataArray[];
 
for(i=0;i<=Data;i++)
{
  DataArray[i] = /*corresponding data point*/;
}


but this leaves me with zero in every index..

what an I missing here??
Last edited on
Arrays cannot resize, are evil, and are a hassle to deal with.

Use std::vector instead, it does what you want and with many more features; it does all the evil stuff for you.

http://www.cplusplus.com/vector

1
2
3
4
5
6
7
#include <vector>
using namespace std;

//...

vector<int> MyVectorOfInts;
MyVectorOfInts.resize(/*new size*/ 25, /*data to fill with*/ CorrespondingDataPoint);
Last edited on
cool! didnt know that about arrays, didnt know they couldnt resize either ;) got it running, thanks!
Check chapter about dynamic memory in a tutorial of this site, i think it wil be easier.
Topic archived. No new replies allowed.