初始化程序列表作为数组的函数参数传递 [英] Initialiser list passed as function parameter for array

查看:253
本文介绍了初始化程序列表作为数组的函数参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何进行这项工作:

void foo(uint8_t a[]) { ... }

foo({0x01, 0x02, 0x03});

这给了我一个错误:

error: cannot convert '<brace-enclosed initializer list>' to 'uint8_t* {aka unsigned char*}' for argument '1'
                                                     ^


推荐答案

到目前为止,答案尚未解决以下主要问题:签名

The answers so far haven't addressed the main problem with the question: In the signature

void foo(uint8_t a[])

a 不是数组,而是指向 uint8_t 的指针。尽管事实上 a 的声明使它看起来像一个数组。错误消息甚至指出了这一点:

a is not an array, but a pointer to a uint8_t. This is despite the fact that the declaration of a makes it look like an array. This is even pointed out by the error message:

cannot convert '<brace-enclosed initializer list>' to 'uint8_t* {aka unsigned char*}'

因此,同样不允许您执行以下操作:

So, in the same way you are not allowed to do this:

uint8_t *a = {0x01, 0x02, 0x03}; // Eek! Error

您不能调用 foo({0x01,0x02,0x03} ); 具有上面的签名。

You can't call foo({0x01, 0x02, 0x03}); With the signature above.

我建议您花一些时间阅读C风格的数组以及它们的用法

I suggest you take some time to read up on C-style arrays and how they are not first-class citizens in C++.

从您对自己的问题发布的答案来看,您似乎正在寻找一种适用于固定大小数组的函数。但是,不要通过价值来传递它!我建议使用以下声明:

From the answer you posted to your own question, it seems that you are looking for a function that works for fixed-size arrays. But don't pass it by value! I recommend using the following declaration:

void foo(std::array<uint8_t, 3> const &a);

这篇关于初始化程序列表作为数组的函数参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆