简体   繁体   中英

initilize a struct array in a class constructor in c++

I have a struct in my header file

 struct Foo{
     timeval t;
     struct Bar b;
 }

and i also have another one for Bar in the same header file, and I have declared a class in the header file as well.

 class Layer{
      public:
              ...
              ...
      private:
              struct Foo myarray[];
 }

I want to declare an array of Foo in my header file and initialize it in my class constructor

 Layer::Layer(unsigned int size)
 {
       myarray = new Foo[size];
 }

but that returns an error when compiling. error: incompatible types in assignment of 'Foo*' to 'Foo [0]'

any idea how to fix this?

That's not initializing the array, it's assigning it. To initialize it, you need a member initializer:

Layer::Layer(unsigned int size) : myarray(new Foo[size]){}

However, that won't compile, since you have an array, which needs to be initialized with one size known at compile-time (via an initializer list if the dimension isn't specified), and that size can't change. Use a vector instead:

std::vector<Foo> myarray;

Layer::Layer(unsigned int size) : myarray(size){}

If the vector isn't an option, you at least need a pointer in order to new it, but then stuff with the rule of three/five starts applying and it all becomes a mess. Stick to the vector if you can.

struct Foo myarray[]; should be struct Foo *myarray; if you're going to go with it in a dynamic approach. Otherwise, if you want it to be an unspecified static I think it has to have an initialization list.

Change the declaration of myArray to read:

struct Foo * myArray;

You can access the array as normal using the index operator ( eg myarray[index] ). You must make sure you don't access it out of bounds, ie index must not be less than 0 or greater than size :

myarray = new Foo[size];
myarray[0];  // Fine
myarray[-1];  // Crash!

myarray[size - 1];  // Also fine
myarray[size];  //  Another crash!

You must also ensure when you delete it you use the delete[] operator instead of the normal delete operator:

delete[] Foo;

The reason your code fails is because the compiler needs to know the size of the array at compile time, and you are trying to allocate the size at runtime. Changing it to a pointer tells the compiler you intend to point at a memory address. When you create an array using:

myarray = new Foo[size];

A new array is allocated in memory, and myarray now points to the address of that array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM