简体   繁体   中英

How to declare and pass a structure during function invocation?

It is very common to declare and pass a basic data-type variable during a function invocation, can we achieve something similar with the structures? Below code explains my question better.

struct s 
{
    int i;
    char c;
};

void f(int i)
{
    return;
}

void g(struct s s1)
{
    return;
}

int main()
{
    int i = 5;  // possible
    struct s s1 = {1, 'c'}; // possible

    f(i);   // possible
    g(s1);  // possible

    f(5);   // possible
    g({1, 'c'});    // not possible, is there any alternative way ?

    return 0;
}

First of all, as a rule of thumb you should avoid passing structs by value, because that's slow and takes up lots of memory. A better interface would be:

void g (struct s* s1)
...
g(&s1);

To answer the question, you may use a compound literal :

g( (struct s){1, 'c'} );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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