如何在函数调用期间声明和传递结构?

问题描述 投票:1回答:1

在函数调用期间声明并传递基本数据类型变量是很常见的,我们能在结构上实现一些相似的东西吗?下面的代码更好地解释了我的问题。

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;
}
c function struct parameter-passing compound-literals
1个回答
3
投票

首先,根据经验,应避免按值传递结构,因为这很慢并且会占用大量内存。更好的界面是:

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

要回答这个问题,您可以使用复合文字

g( (struct s){1, 'c'} );
© www.soinside.com 2019 - 2024. All rights reserved.