Is it possible, in C, to write in one line a call to a function that has an array of strings (ie ptr) or int, or … as parameter?

huangapple go评论57阅读模式
英文:

Is it possible, in C, to write in one line a call to a function that has an array of strings (ie ptr) or int, or ... as parameter?

问题

无法在不进行变量声明的情况下直接调用函数 my_foo1 或 my_foo2。函数 my_foo1 需要一个字符指针的指针作为参数,而函数 my_foo2 需要一个整型指针作为参数。要调用这些函数,需要提供相应类型的变量或值作为参数,因此无法避免变量声明。
英文:

Let's consider these two functions :

void my_foo1(char ** my_par, int size) {
    for (int i=0; i<size; i++) printf("%s \n",my_par[i]);
}

void my_foo2(int * my_par, int size) {
    for (int i=0; i<size; i++) printf("%d \n",my_par[i]);
}

To call them, variables are declared and initialized. And after, function are called on a second line with these variables.

char * (my_strs[3])={"hello","world","!!!!"};
my_foo1(my_strs,3);

int my_ints[3]={1,2,3};
my_foo2(my_ints,3);

Is it possible to write something like :

my_foox(????,3)

and avoid the variable declaration ?

答案1

得分: 10

看起来你正在寻找的是复合文字

my_foo1((char *[]){"hello","world","!!!!"},3);
my_foo2((int []){1,2,3},3);

请注意,这种文字的生命周期与其包围的范围相同。

英文:

It seems like what you're looking for is a compound literal:

my_foo1((char *[]){"hello","world","!!!!"},3);
my_foo2((int []){1,2,3},3);

Note that such literals have the lifetime of their enclosing scope.

答案2

得分: 2

你可以使用复合文字示例:

void my_foo2(int *my_par, int size) {
    for (int i = 0; i < size; i++) printf("%d \n", my_par[i]);
}

my_foo2((int[]){1, 2, 3}, 3);

在函数foo2的调用中,具有类型int[3]的复合文字被隐式转换为其第一个元素的类型为int *的指针。

请注意,由于函数不会更改传递的数组,因此最好像这样声明它:

void my_foo2(const int *my_par, int size) {
    for (int i = 0; i < size; i++) printf("%d \n", my_par[i]);
}
英文:

You can use compound literals as for example

void my_foo2(int * my_par, int size) {
    for (int i=0; i&lt;size; i++) printf(&quot;%d \n&quot;,my_par[i]);
}

my_foo2( ( int [] ){ 1, 2, 3 }, 3 );

In the call of the function foo2 the compound literal having the type int[3] is implicitly converted to a pointer of the type int * to its first element.

Pay attention to as the function does not change the passed array then it will be better to declare it like

void my_foo2( const int * my_par, int size) {
    for (int i=0; i&lt;size; i++) printf(&quot;%d \n&quot;,my_par[i]);
}

huangapple
  • 本文由 发表于 2023年2月13日 23:57:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75438290.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定