void foo(int (&refArr)[10])
{
size_t size = sizeof(refArr); // returns 10*sizeof(int)
}
Today Jonathan asked how to return a reference to an array of fixed size. I took a quick look at the spec and saw that returning a reference to an array is allowed, but I couldn't find how.
Well, it turns out that is looks like this:
const int (&getArray() const)[10]
{
return array_;
}
Fun!
15 comments:
Total fun!! :++)
hahaha
i just.. :++) while(TRUE)
ps. thanx for this post, i was looking actually for the reference to array as a parameter
Awesome, I was looking for this too. Make me question the code I'm writing ;)
Thanks for this. Say I have a reference to an nxn matrix. Is it possible to create a reference to an matrix (n/2)x(n/2) from it? I'm thinking of using this technique to construct hadamard matrices
No. The array is contiguous in memory and therefore the (n/2)x(n/2) array would be slices.
Hi there, thanks for this explanation!
Thanks a lot for the post. I had been stuck at a program in which I was trying to reference an array. Your method worked. Now my program is done. Again thanks a lot!!!!!!!!!!!!!!
Many thanks to you, and to Google!
Whoa! Thanks for this. You simply enlighten me about references to array. I can now answer my assignment in school. Keep it up.
Thanks for this useful knowledge.
http://www.unixwiz.net/techtips/reading-cdecl.html
to understand how to read that
hi, where can I find the standard's description to "reference to fixed-size array" and "the syntax of return a array reference"? thanks.
The syntax for a reference to an array can be found in the standard at 8.5.3 References.
You can slightly improve the syntax by a typedef:
struct Test {
typedef int Array10[10];
Array10 array;
const Array10& getArray() const { return array;}
};
Post a Comment