如何通过一个常量数组常量到需要一个指针,而无需使用一个变量C / C ++函数? [英] How to pass a constant array literal to a function that takes a pointer without using a variable C/C++?

查看:139
本文介绍了如何通过一个常量数组常量到需要一个指针,而无需使用一个变量C / C ++函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个原型,看起来像这样:

If I have a prototype that looks like this:

function(float,float,float,float)

我可以通过数值是这样的:

I can pass values like this:

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天全站免登陆