我该怎么做这样的事情some_function({1,1,1,1})? [英] How do I do something like this some_function({1,1,1,1})?

查看:132
本文介绍了我该怎么做这样的事情some_function({1,1,1,1})?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以说我有一个函数的原型是这样的: INT FUNC(INT * A),它接受一个数组作为参数

Lets say I have a function with prototype like this: int func(int * a), and it accepts an array as an argument.

我如何做没有显示错误比比皆是编译:FUNC({1,1,1,1})

How do I do this without the compiler showing errors everywhere: func({1,1,1,1})

推荐答案

所有你需要的是一个(INT [])投:

All you need is an (int[]) cast:

#include <iostream>

static void f (int* a) {
  while (*a) std::cout << *a++ << "\n" ;
  }

int main() {
  f ((int[]){1,2,3,4,0}) ;
  }

这code输出

1
2
3
4

它可以用C太 - 见此ideone链接

更新补充:我张贴了一个新问题这个结构的合法性,和垫的回答是值得一读,如果你有兴趣之类的话。简单地说,它似乎只在C99有效,但有些编译器允许它在所有的C / C ++的变种的延伸。

Updated to add: I posted a new question about the legality of this construct, and Mat's answer is worth reading if you're interested in that kind of thing. Briefly, it seems that it is valid only in C99, but that some compilers allow it as an extension in all C/C++ variants.

这篇关于我该怎么做这样的事情some_function({1,1,1,1})?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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