How to Pass Array by Reference?

15 03 2009


We used to use arrays, a lot. But did you ever tried how to pass array by reference to another function? Yes. Its a bit tricky.

arraybyreference


Receiving arrays by reference have special syntax. The arrayname and & symbol should be enclosed in parenthesis. And you should specify the size of array. Have a look at the following code snippet.

// Receive Array by reference.
void GetArray( int (&Array) [10] )
{
}

// Test array by reference.
void CRabbitDlgDlg::TestArray()
{
    // Pass array by reference.
    int Array[10] = { 0 };
    GetArray( Array );
}


Indeed, you can pass the array as pointer and then use it. But if you ever need to pass an array by reference, then remember this tip.


Targeted Audience – Beginners.

Advertisements

Actions

Information

5 responses

14 04 2009
Marko

What about non sized arrays? Like void ( int (&arrays)[] ); Please specify every details your suggestion. Thansk

15 04 2009
Jijo.Raj

Hi Marco,

Array should specify their size for being passed as reference. I’m really sorry that i missed that point. Thanks for pointing it out.

Regards,
Jijo.

27 08 2009
Mario

Would this be passed by reference, i have something similar with bool array i use for states in my program. I have never specified the size of what i pass.

// Receive Array by reference.
void GetArray( int Array[] )
{
}

// Test array by reference.
void CRabbitDlgDlg::TestArray()
{
// Pass array by reference.
int Array[10] = { 0 };
GetArray( Array );
}

27 08 2009
Mario

Ok i know it will pass by reference, sorry i meant to ask if it is correct i mean if you say [10] or [] isnt it just the address of the first element ?

3 12 2009
Mike

My understanding is an array cannot be passed as a value, and thus, it is always passed as a reference. It may be passed as a pointed as well.

Anyway, a reference ‘&’ isn’t needed, and the subscript value doesn’t matter.

header: function(int array[]);
call: function(array);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s




%d bloggers like this: