C++ 将数组的引用传递给函数
给函数 void main() 和 void hello(byte* a[4]).Main 函数有一个四个字节的数组.数组的引用需要传递给函数 hello 进行操作.我希望正确的语法是:
Given to functions void main() and void hello(byte* a[4]). Main function has an array of four bytes. The array's reference needs to be passed to the function hello for manipulation. I would expect the right syntax to be:
void hello(byte* a[4]){
// Manipulate array
a[0] = a[0]+1;
}
void main(){
byte stuff[4] = {0,0,0,0};
hello(&stuff);
// hopefully stuff is now equal {1,0,0,0}
}
或者我看到其他人使用这种形式的 decaration:
Alternatively I see others using this form of decaration:
void hello(byte (&a)[4])
这是正确的做法吗?
推荐答案
这里有许多不同的选项,具体取决于您想在这里做什么.
There are many different options here depending on what you want to do here.
如果你有一个 byte
对象的原始数组,你可以把它传递给一个像这样的函数:
If you have a raw array of byte
objects, you can pass it into a function like this:
void hello(byte arr[]) {
// Do something with arr
}
int main() {
byte arr[4];
hello(arr);
}
将数组传递给函数的机制(将指向数组第一个元素的指针传递给函数)的功能类似于按引用传递:您对 arr所做的任何更改
hello
中的 code> 将保留在 main
中,即使您没有明确传递对它的引用.但是,hello
函数不会检查数组的大小是否为 4 - 它会将 任意 个字节的数组作为输入.
The mechanism by which the array is passed into the function (a pointer to the first element of the array is passed to the function) functions similarly to pass-by-reference: any changes you make to arr
in hello
will stick in main
even though you didn't explicitly pass in a reference to it. However, the hello
function won't check whether the array has size four or not - it'll take in as input an array of any number of bytes.
你也可以写
void hello(byte (&arr)[4]) {
// ...
}
int main() {
byte arr[4];
hello(arr);
}
语法 byte (&arr)[4]
表示对四个字节数组的引用".这将通过引用显式地将数组传递给 hello
,并且它将检查数组的大小以确保它是正确的.然而,这是非常不寻常的语法,在实践中很少见.
The syntax byte (&arr)[4]
means "a reference to an array of four bytes." This explicitly passes the array by reference into hello
, and it will check the size of the array to make sure it's correct. However, this is very unusual syntax and rarely seen in practice.
但也许最好的主意是不使用原始数组并使用 std::array
代替:
But perhaps the best idea is to not use raw arrays and to use std::array
instead:
void hello(std::array<byte, 4>& arr) {
// Do something with arr
}
int main() {
std::array<byte, 4> arr;
hello(arr);
}
现在,字节数组的语法中没有奇怪的括号,也不必担心大小检查.一切都得到了正确处理,因为 std::array
是一种对象类型,它具有常规对象类型的所有优点.我建议采用最后一种方法,而不是其他方法.
Now, there's no weirdnesses about strange parentheses in the syntax for arrays of bytes and there's no worries about size checking. Everything is handled properly because std::array
is an object type that has all the advantages of regular object types. I'd recommend going with this last approach above all the other ones.
相关文章