3

I have an object that has an array attribute, say (*obj).some_array;, where some_array is an integer array.

I know that we can alias simply like so:

int test = 10;
int &alias = test;

However, how can I alias to an array of an object, similarly to above but for obj's some_array?

apple
  • 63
  • 1
  • 4

2 Answers2

7

If obj->some_array is of type int[LEN] you can just do:

int (&alias)[LEN] = obj->some_array;

To understand this weird syntax you could use theClockwise/Spiral Rule, a way you could read declarations you're not familiar it (see here).

int &alias[LEN] (which is the same as int &(alias[LEN]) would be an array of LEN references to int.
int (&alias)[LEN] is, instead, a reference to an array of LEN ints


Note that what you call alias is called a reference in C++!

Community
  • 1
  • 1
peoro
  • 25,562
  • 20
  • 98
  • 150
  • 1
    C's declaration syntax is not driven by the Clockwise/Spiral rule. Complex declarators are built up in a logical and consistent way from simpler declarators. The clockwise / spiral rule is an aide-memoire that some people (not me!) use to help them interpret complex declarations. The rationale is to have a declaration syntax that mirrors usage. It helps especially to get array bounds the correct way around in multidimensional arrays. Your answer makes it seem like the syntax was devised to make use of an arbitrary rule just for the sake of it. – CB Bailey Feb 06 '11 at 18:31
  • Yes, while it may initially seem counter-intuitive I think it helps to show that there is some logic behind the syntax. Just for info, here's where I last explained ["declaration follows usage"](http://stackoverflow.com/questions/1371898/is-int-array32-a-pointer-to-an-array-of-32-ints-or-an-array-of-32-pointers-to/1371931#1371931) . Or [here](http://stackoverflow.com/questions/3707096/spiral-rule-and-declaration-follows-usage-for-parsing-c-expressions) . – CB Bailey Feb 06 '11 at 18:47
0

Assuming some_array is an integer array:

int *alias = obj.some_array;
Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
  • What @Oli Charlesworth said. Besides the thing your `alias` points to is not of the same type of `obj.some_array`, since `obj.some_array` is an `int[LEN]`, while `*alias` is an `int`. – peoro Feb 06 '11 at 18:21