Frage

I want to do something like

int &a = *(new int[10]);
// access all the indices from this reference somehow.

All I can do is something like,

int *b = &a;
b[1] = 10;

Can I do it using reference? If no, why?

War es hilfreich?

Lösung

You have to use pointers because the array index operator in C++ is only defined for pointers (and user defined classes that overloaded that operator). However the pointer can simply be a temporary:

(&a)[1] = 10;

If you want to avoid pointers then you can simply use std::array or std::vector instead:

std::array<int, 10> a;
a[1] = 10;

std::vector<int> v(n);
v[1] = 10;

Andere Tipps

Yes, you can certainly do so, but it goes against the grain: References are not expected to be used for getting other elements of an array but the referenced element. Please refrain.

You can use a reference:

int (&a)[10] = (int (&)[10])*new int[10];

That said, you still need to delete[] &a, and if you know the array size and it's not humongous you can just create a normal stack-based array. You can't create a reference to an array of unknown/runtime-determined length. Given you can also index pointers, this is of extremely limited practical use (mainly for passing the array to templates that themselves bind references to it, normally so they can implicitly access the array size).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top