Tuesday, June 07, 2005

C++ reference to an array

A number of years ago I remember learning how to pass a reference to an array of fixed size to a function in C++. The C++ Primer by Stan Lippman and Josee Lajoie discuss how to do this in section 7.3 (Functions - Argument Passing). It looks like this:

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!

Labels:

8 Comments:

Anonymous Anonymous said...

Total fun!! :++)

10/9/08 1:31 AM  
Anonymous Marina said...

hahaha

i just.. :++) while(TRUE)


ps. thanx for this post, i was looking actually for the reference to array as a parameter

12/15/08 2:51 PM  
Anonymous Anonymous said...

Awesome, I was looking for this too. Make me question the code I'm writing ;)

1/14/09 12:47 PM  
Blogger Carl said...

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

4/22/09 7:44 PM  
Blogger Kevin Heifner said...

No. The array is contiguous in memory and therefore the (n/2)x(n/2) array would be slices.

4/22/09 9:53 PM  
Anonymous GiM said...

Hi there, thanks for this explanation!

4/29/09 9:25 AM  
Blogger Saurav Deb Purkayastha said...

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!!!!!!!!!!!!!!

5/28/09 4:18 AM  
Anonymous manuell said...

Many thanks to you, and to Google!

7/7/09 5:41 AM  

Post a Comment

<< Home