empty array declaration

Hello,
How else can I init this array pls ?

class Ray {
public:
int myArray[]; // since this is NOT legal !
Ray(int);
};

Ray::Ray(int i){
for(int x=0; x<=i; i++)
{
myArray[x] = x +1;
}



closed account (N36fSL3A)
You are required to set the value of an array as soon as you declare it's existence.

So you can do this a number of ways.
1
2
const int var = 10;
int myArray[var];


1
2
#define val 10
int myArray[val];


int myArray[10];
Last edited on by Fredbill30
You can use either std::vector instead of the array. For example

class Ray {
public:
std::vector<int> myArray;
Ray(int);
};

Ray::Ray(int i){
myArray.reserve( i + 1 );
for(int x=0; x<=i; x++)
{
myArray.push_back( x +1 );
}


Or you shoud dynamically allocate the array

class Ray {
public:
int *myArray;
Ray(int);
};

Ray::Ray(int i){
myArray = new int[i + 1];
for(int x=0; x<=i; x++)
{
myArray[x] = x +1;
}

Last edited on
thanks so much.... Vlad
Topic archived. No new replies allowed.