gpt4 book ai didi

C++ 引用数组

转载 作者:可可西里 更新时间:2023-11-01 18:02:28 26 4
gpt4 key购买 nike

我想知道如何让这段代码工作?

#include <iostream>
using namespace std;

void writeTable(int (&tab)[],int x){
for(int i=0;i<x;i++){
cout << "Enter value " << i+1 <<endl;
cin >> tab[i] ;
}
}


int main(void){
int howMany;
cout << "How many elemets" << endl;
cin >> howMany;

int table[howMany];
int (&ref)[howMany]=table;
writeTable(ref,howMany);
return 0;
}

这里是我遇到的错误:

|4|error: parameter ‘tab’ includes reference to array of unknown bound ‘int []’|
|18|error: invalid initialization of reference of type ‘int (&)[]’ from expression of type ‘int [(((unsigned int)(((int)howMany) + -0x00000000000000001)) + 1)]’|
|4|error: in passing argument 1 of ‘void writeTable(int (&)[], int)’|

感谢帮助

最佳答案

如果你打算传递数组的大小,那么移除引用

void f(int a[])

相当于

void f(int* a)

如果担心的话,不会进行复制。

如果你想通过引用获取一个数组,那么你必须指定维度。例如

void f(int (&a)[10])

当然,两者中最好的是第三种解决方案,即使用 std::vector 并通过引用传递它们,如果需要,可以引用 const 或按值传递。

关于C++ 引用数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3949715/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com