C++ 通过引用传递字符数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12987760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:49:59  来源:igfitidea点击:

Passing char array by reference

c++arrayspass-by-reference

提问by Naruto

I am passing a char array by reference but when I return from function and print the array, it displays nothing. What am I doing wrong?

我通过引用传递一个字符数组,但是当我从函数返回并打印数组时,它什么也不显示。我究竟做错了什么?

#include <iostream>

using namespace std;

void func(char []);
int main()
{
   char a[100];
   func(a);

   cout << a<<endl;
   return 0;
}

void func(char *array)
{
   array="Inserting data in array a";
   cout << array<<endl;
}

Regards

问候

采纳答案by Benjamin Lindley

You're not passing the array by reference (nor should you, it will do you no good here). You are passing a pointer to its first element. You then reassign that pointer to point to something else inside the function. This has no effect on the array. If you want to change the contents of the array, then you need to copy data to the place that the pointer points to. You can use strcpy or similar for that:

你不是通过引用传递数组(你也不应该,这对你没有好处)。您正在传递指向其第一个元素的指针。然后您重新分配该指针以指向函数内的其他内容。这对阵列没有影响。如果要更改数组的内容,则需要将数据复制到指针指向的位置。你可以使用 strcpy 或类似的:

strcpy(array, "Inserting data in array a");

As a side comment, but a very important one. We don't need to deal with things like this in C++ anymore. That's how you do things in C. Here's how we do things in C++:

作为旁注,但非常重要。我们不再需要在 C++ 中处理这样的事情。这就是你在 C 中做事的方式。 以下是我们在 C++ 中做事的方式:

#include <string>
#include <iostream>

void func(std::string & str)
{
    str = "Inserting data into the string";
    std::cout << str << std::endl;
}

int main()
{
    std::string a;
    func(a);
    std::cout << a << std::endl;
}

回答by 0x499602D2

What you can probably do is:

你可能会做的是:

void func( char (& array)[10] ) {

}

Which translates to: pass an array ([..]) of 10 ( [10]) characters ( char) by reference ( (& ..)).

转换为:通过引用 ( )传递[..]10 ( [10]) 个字符 ( char)的数组( (& ..))。

回答by Kirill Kobelev

You can pass a pointer by reference. To do this you need the following syntax:

您可以通过引用传递指针。为此,您需要以下语法:

void func(char *&array)
{
    // ....
}

Inside the function you use this parameter as a simple pointer. Only if it is modified, these changes are visible outside.

在函数内部,您将此参数用作简单的指针。只有经过修改,这些变化才会在外面可见。

回答by roohan

Try the following:

请尝试以下操作:

void function(char* MyArray)
{
    MyArray = "Hello World";
    std::cout << "Address of MyArray inside function: " << (void*)MyArray << std::endl;
}

int main()
{
    char MyArray[10];
    std::cout << "Address of MyArray outside function: " << (void*)MyArray << std::endl;
    function(MyArray);
    std::cout << "Address of MyArray outside function: " << (void*)MyArray << std::endl;

    std::cin.get();
    return 0;
}

With this you will see that the pointer to your array is only a copy inside the function. With assigning "Hello World" you only change the adress of the copy but not the adress of your array in the main function.

有了这个,您将看到指向数组的指针只是函数内部的一个副本。通过分配“Hello World”,您只能更改副本的地址,而不能更改主函数中数组的地址。

This example would actually work because this way you dont have copy of your pointer within the function:

这个例子实际上可以工作,因为这样你就没有函数内的指针副本:

void function(char** MyArray)
{
    *MyArray = "Hello World";
    std::cout << "Address of MyArray inside function: " << (void*)*MyArray << std::endl;
}

int main()
{
    char* MyArray = 0;
    std::cout << "Address of MyArray outside function: " << (void*)MyArray << std::endl;
    function(&MyArray);
    std::cout << "Address of MyArray outside function: " << (void*)MyArray << std::endl;

    std::cin.get();
    return 0;
}

But this is still bad style. When working with character arrays you should do something like this:

但这仍然是糟糕的风格。使用字符数组时,您应该执行以下操作:

void function(char* MyArray)
{
    strcpy(MyArray, "Hello World");
    std::cout << "Address of MyArray inside function: " << (void*)MyArray << std::endl;
}

int main()
{
    char* MyArray = 0;
    MyArray = new char[15];

    std::cout << "Address of MyArray outside function: " << (void*)MyArray << std::endl;
    function(MyArray);
    std::cout << "Address of MyArray outside function: " << (void*)MyArray << std::endl;

    delete [] MyArray;

    std::cin.get();
    return 0;
 } 

But as others mentioned I would use std::string and pass it by reference also instead of using character arrays. Because character arrays are unsafe compared to std::string. Like this:

但正如其他人提到的,我会使用 std::string 并通过引用传递它,而不是使用字符数组。因为与 std::string 相比,字符数组是不安全的。像这样:

void function(std::string& MyString)
{
    MyString = "Hello World";
}

int main()
{
    std::string MyString;
    function(MyString);

    std::cin.get();
    return 0;
}

回答by radato

I used the answers above but I had to extend it, so I could print out the array's actual size like so:

我使用了上面的答案,但我不得不扩展它,所以我可以像这样打印出数组的实际大小:

template<size_t n> void foo(char (&array)[n])
{
    // ...
    std::cout << "array size: " << n << std::endl;
    // ...
}

回答by Chef Gladiator

Reference to native array is one of the very powerful C++ weapons. Plus templates. Here is one, perhaps non trivial but still simple example.

对原生数组的引用是非常强大的 C++ 武器之一。加上模板。这是一个,也许不平凡但仍然很简单的例子。

// set all element of a given native array reference 
// to the same value
// return the reference to the same array
    template<typename T, size_t N, typename array_type = T[N] >
    inline
        array_type&  /* return reference to T[N] */
        all_val 
         (  T(&arf)[N],  /* arg reference to T[N] */
            T val   )
    {
        // range for() works on native arrays
        // begin(arf) / end(arf)
        // work as expected
        for (auto & elem : arf) {
            elem = val ;
        }
        // array can not be returned by value
        // but this is allowed in standard C++
        // return type is native array reference
        return arf;
    }

When using the above, one should think and preserve returned type as native array reference.

使用上述方法时,应考虑并保留返回类型作为本机数组引用。

        using charray_type = char[0xF];
        charray_type charray;
        // decaying to pointer to T*
        // you do not want this
        auto pointer_to_char = all_val(charray, '*');
        // you do want this
        // preserving the ref to array
        charray_type& charray_ref = all_val(charray, '*');
        // normal native arr usage
        charray_ref[0] = '*';
        assert(charray[0] == charray_ref[0]);

I think this is rather simple and unique to standard C++.

我认为这对于标准 C++ 来说相当简单和独特。

回答by mauve

You are passing a pointer to an array (func (char* array)) and then inside the function you are changing the pointer's value to point to the static string.

您正在传递一个指向数组 ( func (char* array))的指针,然后在函数内部将指针的值更改为指向静态字符串。

You either need to copy the new data into the array by means of strcpy()or pass the pointer to the array by reference:

您需要通过以下方式将新数据复制到数组中strcpy()或通过引用传递指向数组的指针:

void func(char*& array); // reference to pointer

Or:

或者:

strcpy(array, "data");

Better yet use std::vector<>or std::stringinstead.

最好还是使用std::vector<>std::string代替。

回答by Javasist

error first line iostream.h... and secondly you are not inserting any element into array...and you are passing a in your function, you have to pass address of your array into that function, but before that rewrite the code to have something in your array

错误第一行iostream.h... 其次,您没有将任何元素插入数组...并且您正在函数中传递 a,您必须将数组的地址传递到该函数中,但在此之前将代码重写为在你的数组中有一些东西