-2

I received lecture slides for C++ that merely mention these without explaining what they mean and what are their differences:

int (*arr)[]={...};
int *(arr[])={...};
int (&arr)[]={...};
int &(arr[])={...}; // not allowed?

What do each of these mean? I tried running a program with some of these, but I'm getting errors because I don't know what to put in the initialization list.

Leo Jiang
  • 24,497
  • 49
  • 154
  • 284

2 Answers2

6
  • int (*arr)[] = { ... };

    This is not an array at all. This is a pointer to an array of unknown size. Note that this a scalar type. It is just a data pointer, no different in nature from any other data pointer. Which means that the only way to use { ... } initializer with it is to specify a single value of proper type inside the { ... }. E.g.

    int (*arr)[] = { nullptr };
    

    which is the same as

    int (*arr)[] = nullptr;
    
  • int *(arr[]) = { ... };

    This is indeed an array. The same thing can be expressed as

    int *arr[] = { ... };
    

    This is an array of int * pointers. It size will depend on how many initializers are supplied in { ... }. E.g.

    int *arr[] = { nullptr, &some_int, &some_other_int };
    

    declares arr as an array of 3 pointers of type int *.

  • int (&arr)[] = { ... };

    This is not an array per se. This is a reference to an array of unknown size. Again, the only legal { ... } initializer in this case would be just one lvalue of type int [] inside the { ... }. If the array was declared const, you'd be able to attach it to a temporary array of ints using this syntax, e.g.

    const int (&arr)[] = { 1, 2, 3 };
    

    But without const it is not possible. (I have my doubts about the legality of this even with const though. GCC accepts it.)

  • int &(arr[]) = { ... };

    This is an attempt to declare an array of references. Not allowed.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
2

You need to use the Clockwise/Spiral Rule.

int (*arr)[]={...};  // pointer to array of int
int *(arr[])={...};  // array of int pointers
int (&arr)[]={...};  // a reference to an array of int
int &(arr[])={...};  // an array of int references

The last one though is illegal: Why arrays of references are illegal?

Community
  • 1
  • 1
NathanOliver
  • 171,901
  • 28
  • 288
  • 402