简体   繁体   中英

How to pass an array to a function by reference?

I'm looking how to pass a string/array to a function, I have tried to pass by value, but it doesn't seem to work, I have looked online and seen by reference but that doesn't seem to be working either.

Can anyone help?

You declare a function that takes an array of 10 ints by reference like this:

void f(int (&arr)[10]);

You call it like this

int arr[10];
f(arr);

You can templatize your function

template<class T, int N>
void f(T (&arr)[N]);

If you are using variable size arrays you should use something like this:

void someFunc(char* szString, int cbChars)
{
    for (int nChar == 0; nChar < cbChars; nChar++)
    {   // Do something with the char array
        szString[nChar] = 'A'; // Convert string to "AAAAAA..."
    {
}

void callerFunc()
{
    char szString[255];
    // read file...
    // put file contents in szString
    // and call the above function passing the string 'by reference'
    someFunc(szString, 255);
}

That is, just pass a pointer to the array (must be the same type) and its size (so you know where to stop and avoid exceptions).

You can do the same for any array of any data-type, there's a good tutorial on pointers: http://www.cplusplus.com/doc/tutorial/pointers/

If you're using a recent compiler like recent gcc and visual studio (that provide C++11 containers) you could use instead of a raw array a std::array and make things more clear on reading.

Here is Armen Tsirunyan answer with std::array :

void f( std::array<int,10> & arr );

You call it like this

std::array<int,10> arr;
f(arr);

You can templatize your function

template<class T, int N>
void f( std::array<T,N> & arr );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM