给出函数void main()和void hello(byte * a [4]).主函数具有四个字节的数组.数组的引用需要传递给函数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} }或者,我看到其他人使用这种形式的贬低行为:
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); }将数组传递给函数的机制(指向数组第一个元素的指针传递给函数)的功能类似于按引用传递:您对
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.
更多推荐
C ++将对数组的引用传递给函数
发布评论