2015-07-01 18 views
8

L'obiettivo è quello di passare una matrice costante, (che rappresentano le variabili membro del parametro corrispondente struttura) come {{"network", "lan"}, {"dhcp", "true"}} come parametro quando si chiama una funzione come:Come passare array letterale come argomento di input della funzione?

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

Ho provato il seguente codice ma restituisce errori nel 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; 
} 

Come posso farlo nel modo giusto?

+0

letterali composti, forse? –

+0

"ma restituisce errori nella compilazione:" -> invia il messaggio di errore. – chux

+1

Passaggio 1, usare 'int ubus_call (const char * obj, metodo const char *, const struct ubus_args * u_args, size_t size_args) ' – chux

risposta

7

Se si dispone di un C99 e di un compilatore supportato, è possibile utilizzare compound literals per completare il lavoro.

si può riscrivere la chiamata di funzione come

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

e funzionerà.

LIVE DEMO

BTW, la firma raccomandata di main() è int main(void).

9

Ecco il programma completo, puoi provarlo.

#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; 
} 

Il programma è testato su GNU GCC v4.8.3 compilatore on-line.

+2

Se non è inteso per 'ubus_call' modificare le stringhe, usare' const struct ubus_args' sia nel parametro function che nel literal composto –

Problemi correlati