简体   繁体   English

如何通过引用将数组传递给函数?

[英]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: 您可以通过引用声明一个包含10个int数组的函数,如下所示:

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/ 您可以对任何数据类型的数组执行相同的操作,有一个很好的指针教程: 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. 如果您正在使用最近的编译器,例如最近的gcc和visual studio(提供C ++ 11容器),您可以使用std :: array而不是原始数组,并在阅读时更加清晰。

Here is Armen Tsirunyan answer with std::array : 这是使用std :: array的Armen Tsirunyan回答:

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 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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