如何在不使用变量 C/C++ 的情况下将常量数组文字传递给采用指针的函数? [英] How to pass a constant array literal to a function that takes a pointer without using a variable C/C++?

查看:36
本文介绍了如何在不使用变量 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++ 的情况下将常量数组文字传递给采用指针的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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