C:“动态"将数组传递给函数 [英] C: Passing an array into a function 'on the fly'

查看:90
本文介绍了C:“动态"将数组传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,我想将一个char *数组传递给它,但我不想为此创建变量,就像这样:

I have a function, and I want to pass an array of char* to it, but I don't want to create a variable just for doing that, like this:

char *bar[]={"aa","bb","cc"};
foobar=foo(bar);

要解决这个问题,我尝试了以下方法:

To get around that, I tried this:

foobar=foo({"aa","bb","cc"});

但是它不起作用.我也尝试过这个:

But it doesn't work. I also tried this:

foobar=foo("aa\0bb\0cc");

它会编译并显示警告,如果我执行该程序,它将冻结.
我也尝试过使用星号和&符,但是我无法使其正常工作.

It compiles with a warning and if I execute the program, it freezes.
I tried playing a bit with asterisks and ampersands too but I couldn't get it to work properly.

有可能吗?如果可以,怎么办?

Is it even possible? If so, how?

推荐答案

是的,您可以使用复合文字.请注意,您将需要为函数提供某种方式来了解数组的长度.一种是在末尾使用NULL.

Yes, you can use a compound literal. Note that you will need to provide some way for the function to know the length of the array. One is to have a NULL at the end.

foo((char *[]){"aa","bb","cc",NULL});

此功能已在C99中添加.

This feature was added in C99.

这篇关于C:“动态"将数组传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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