kdubs
kdubs

Reputation: 1722

Array of pointers vs ** : why does one give an error?

I'm trying to create an array of pointers (please don't suggest std::array, etc., there's other things going on). From C I thought the following code was equivalent, and I wanted to use the [] notation because I'm trying to stress that it is an array. I the get the following error, however.

g++ -c x.C

x.C: In constructor 'more_data::more_data()':

x.C:11: error: incompatible types in assignment of 'data*' to 'data* [0]'

class data { int a;int b; };
class more_data {
  public:
    data * bad[];
    data ** good;

   more_data(){
     good = new data * [ 5 ] ;
     bad = new data * [ 5 ] ;
   }
};

Upvotes: 0

Views: 261

Answers (3)

yizzlez
yizzlez

Reputation: 8805

In C++, the standard is for an array to have a fixed size at compilation. data *bad [] creates an array of pointers. You must initialize an array in C++ in the constructor initializer:

data * bad [CONST];
more_data: bad() {
    //initialize individual elements
}

Upvotes: 0

Quentin
Quentin

Reputation: 63144

You can't assign arrays. But even before thinking about assigning bad, GCC rightly signals "warning: ISO C++ forbids zero-size array 'bad'", because your bad array has no size.

If you want to document that your pointer points to an array, name it accordingly : arrFoo, fooArr, foos...

Better yet, use std::vector<data*> if you can. If you really can't, as always make sure to follow the Rule of Five, and fon't forget to delete[].

Upvotes: 4

Alexander Balabin
Alexander Balabin

Reputation: 2085

data *bad[];

is a zero-sized array of pointers. Most compilers will reject this code and it is not standard (please correct me if that changed recently). The only use of this construct is an old C-hack to declare variable length structures.

Upvotes: 3

Related Questions