如何在C++中返回数组而不是指针?

huangapple go评论64阅读模式
英文:

How to return array in C++ not a pointer?

问题

我知道如何返回一个指向数组第一个元素的指针,但我的问题是,如果可能的话,我应该如何返回实际的数组,而不是指向该数组的指针。

类似地,我应该如何通过引用传递数组给一个函数:

void print_arr(int (&arr)[3])
{
    for (size_t i = 0; i < 3; ++i)
        std::cout << arr[i] << ' ';
}

我想到了类似这样的东西:

int(&)[3] func(int (&arr)[3])
{
    // 一些代码...
    return arr;
}

但它不起作用。这里是在线编译器中的代码。

英文:

I know how to return a pointer which points to the first element of the array, but my question is how would I return actual array, not a pointer to that array if that is even possible.

Similarly to how would I pass array to a function by reference:

void print_arr(int (&amp;arr) [3])
{
	for(size_t i = 0; i &lt; 3; ++i)
		std::cout &lt;&lt; arr[i] &lt;&lt; &#39; &#39;;
}

I thought something like this:

int(&amp;)[3] func(int (&amp;arr) [3])
{
    // some code...
    return arr;
}

But it doesn't work. Here is the code in online compiler.

答案1

得分: 0

你不能在C或C++中直接返回数组。一个方法是声明一个包含数组的struct/union来绕过这个问题。

union arrayint3 {
    int i[3];
};
arrayint3 func(int(&arr)[3]) {
    arrayint3 arr = {.i = {1, 2, 3}};
    return arr;
}

你也可以返回一个std::array。根据链接的问题和答案:

是否合法通过值返回std::array,像这样?

std::array<int, 3> f() {
    return std::array<int, 3> {1, 2, 3};
}

是的,这是合法的。

英文:

You cannot 'return arrays' directly in C or C++. One way you can use to get around that is declare a struct/union containing the array.

union arrayint3 {
    int i[3];
};
arrayint3 func(int(&amp;arr)[3]) {
    arrayint3 arr = {.i = {1, 2, 3}};
    return arr;
}

You can also return an std::array.
According to the linked Q&A:
> Is it legal to return std::array by value, like so?
>
&gt; std::array&lt;int, 3&gt; f() {
&gt; return std::array&lt;int, 3&gt; {1, 2, 3};
&gt; }
&gt;

> Yes it's legal.

huangapple
  • 本文由 发表于 2023年6月12日 00:33:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76451458.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定