3

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

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

1 回答 1

2

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

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

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

g( (struct s){1, 'c'} );
于 2020-05-14T08:41:00.737 回答