Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

c

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:

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?

like image 568
imen bhiri Avatar asked Jul 01 '15 14:07

imen bhiri


Video Answer


2 Answers

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.

like image 126
Shri Avatar answered Sep 21 '22 09:09

Shri


If you're equipped with a C99 and above supported compiler, you can use compound literals to get your job done.

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).

like image 42
Sourav Ghosh Avatar answered Sep 24 '22 09:09

Sourav Ghosh