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.
-
By default, it is pass by value, unless you pass a pointer to the structure.Jonathan Leffler– Jonathan Leffler2016-04-10 21:49:40 +00:00Commented Apr 10, 2016 at 21:49
-
a structure being passed to a function will always arrive at the function as a pointer to the structure, actually, a cloned pointer to the structure. Note: arrays are NOT passed to a function, rather an address of the array is passed, actually a clone of the address of the array.user3629249– user36292492016-04-12 20:36:06 +00:00Commented Apr 12, 2016 at 20:36
Add a comment
|
3 Answers
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;
}
Comments
You are passing it by value. Everything in a structure is copied.
3 Comments
bengbeng
Can you give an example?
M.M
@bengbeng write your own example. you know how to make a function. use
struct S as parameter instead of int or whatever.Marcin Możejko
Struct is implemented in a way, that a block of a memory is allocated to store it's members. When you pass a struct as argument - you may think about it as copying this block of a memory to a function.