简体   繁体   English

如何传递文字数组作为函数的输入参数?

[英]How to pass literal array as input argument of the function?

The goal is to pass a constant array, (representing the member variables of the corresponding structure parameter) like {{"network", "lan"}, {"dhcp", "true"}} as parameter when calling a function like: 目标是在调用函数时传递一个常量数组(表示相应结构参数的成员变量),如{{"network", "lan"}, {"dhcp", "true"}}作为参数:

ubus_call("router", "client", {{"network", "lan"}, {"dhcp", "true"}}, 2);

I tried the following code but it returns errors in the compilation: 我尝试了以下代码,但它在编译中返回错误:

struct ubus_args {
 char *key;
 char *val;
};

int ubus_call(char *obj, char *method, struct ubus_args u_args[], int size_args) {
 printf("%s\n", obj);
 printf("%s\n", method);
 printf("%s  %s\n", u_args->key, u_args->val);
 return 0;
}

int main ()
{
  ubus_call("router", "client", {{"network", "lan"}, {"dhcp", "true"}}, 2);
  return 0;
}

How I can do that in the proper way? 我怎么能以正确的方式做到这一点?

Here is the complete program, you can try it out. 这是完整的程序,你可以尝试一下。

#include <stdio.h>

struct ubus_args {
    char *key;
    char *val;
};

int ubus_call(char *obj, char *method, struct ubus_args u_args[], int size_args) {
    printf("%s\n", obj);
    printf("%s\n", method);
    printf("%s  %s\n", u_args[0].key, u_args[0].val);
    printf("%s  %s\n", u_args[1].key, u_args[1].val);
    return 0;
}

int main ()
{
    ubus_call("router", "client", (struct ubus_args[2]){{"network", "lan"}, {"dhcp", "true"}}, 2);
    return 0;
}

The program is tested on GNU GCC v4.8.3 online compiler. 该程序在GNU GCC v4.8.3在线编译器上进行测试。

If you're equipped with a C99 and above supported compiler, you can use compound literals to get your job done. 如果您配备了C99及以上支持的编译器,则可以使用复合文字来完成工作。

You can rewrite the function call like 你可以重写函数调用

ubus_call("router", "client", (struct ubus_args[]){{"network", "lan"}, {"dhcp", "true"}}, 2);

and it will work. 它会起作用。

LIVE DEMO 现场演示

BTW, the recommended signature of main() is int main(void) . 顺便说一句, main()的推荐签名是int main(void)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM