C ++将对数组的引用传递给函数

编程入门 行业动态 更新时间:2024-10-23 01:52:39
本文介绍了C ++将对数组的引用传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

给出函数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); }

将数组传递给函数的机制(指向数组第一个元素的指针传递给函数)的功能类似于按引用传递:您对仍会保留在main中,即使您没有显式传递对它的引用.但是,hello函数将不会检查该数组的大小是否为四-将以 any 个字节数的数组作为输入.

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 ++将对数组的引用传递给函数

本文发布于:2023-07-29 00:38:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1235605.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:将对   数组   函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!