简体   繁体   English

将结构传递给函数

[英]Pass a Struct to a Function

When you pass a struct to a function, is it pass by value (similar to regular variables where the value gets cloned), or is it pass by reference (similar to arrays where the actual variable is passed)? 将结构传递给函数时,它是否通过值传递(类似于克隆值的常规变量),还是通过引用传递(类似于传递实际变量的数组)? Can you give an example. 能给我举个例子吗。

In C everything is pass by value, even passing pointers is pass by value. 在C中,一切都是按值传递的,即使传递指针也是按值传递的。 And you never can change the actual parameter's value(s). 而且你永远不能改变实际参数的值。

That is from K&R by the way. 顺便说一句,这是来自K&R。 And I recommend to read that book. 我建议阅读那本书。 Saves you many questions you might post in the future. 为您节省许多可能会在未来发布的问题。

A struct is passed by value: 结构按值传递:

struct S {
    int a,b; 
};

void f(struct S s) {
    printf("%d\n", s.a+s.b); 
    s.a = 0;   /* change of a in local copy of struct  */
}

int main(void) {
    struct S x = { 12,13};
    f(x);
    printf ("Unchanged a: %d\n",x.a);
    return 0;
}

Online demo 在线演示

You are passing it by value. 你是按价值传递的。 Everything in a structure is copied. 结构中的所有内容都被复制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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