How to pass a constant array literal to a function that takes a pointer without using a variable C/C++?(如何在不使用变量 C/C++ 的情况下将常量数组文字传递给采用指针的函数?)
问题描述
如果我有一个看起来像这样的原型:
If I have a prototype that looks like this:
function(float,float,float,float)
我可以传递这样的值:
function(1,2,3,4);
如果我的原型是这样的:
So if my prototype is this:
function(float*);
有什么办法可以实现这样的目标吗?
Is there any way I can achieve something like this?
function( {1,2,3,4} );
只是在寻找一种懒惰的方法来做到这一点而不创建临时变量,但我似乎无法确定语法.
Just looking for a lazy way to do this without creating a temporary variable, but I can't seem to nail the syntax.
推荐答案
您可以在 C99(但不是 ANSI C (C90) 或 C++ 的任何当前变体)中使用 复合文字.有关详细信息,请参阅 C99 标准的第 6.5.2.5 节.举个例子:
You can do it in C99 (but not ANSI C (C90) or any current variant of C++) with compound literals. See section 6.5.2.5 of the C99 standard for the gory details. Here's an example:
// f is a static array of at least 4 floats
void foo(float f[static 4])
{
...
}
int main(void)
{
foo((float[4]){1.0f, 2.0f, 3.0f, 4.0f}); // OK
foo((float[5]){1.0f, 2.0f, 3.0f, 4.0f, 5.0f}); // also OK, fifth element is ignored
foo((float[3]){1.0f, 2.0f, 3.0f}); // error, although the GCC doesn't complain
return 0;
}
GCC 也将此作为 C90 的扩展提供.如果您使用 -std=gnu90
(默认值)、-std=c99
或 -std=gnu99
编译,它将编译;如果使用 -std=c90
编译,则不会.
GCC also provides this as an extension to C90. If you compile with -std=gnu90
(the default), -std=c99
, or -std=gnu99
, it will compile; if you compile with -std=c90
, it will not.
这篇关于如何在不使用变量 C/C++ 的情况下将常量数组文字传递给采用指针的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在不使用变量 C/C++ 的情况下将常量数组文字


基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 我有静态或动态 boost 库吗? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30