I have a question about passing arguments in function. Like I discovered that I can pass arguments of structure in two ways:
First:
name_t* foo(name_t* foo)
{
//do some changes with structure
return foo->something
}
Second:
name_t foo(name_t foo)
{
//do some changes with structure
return foo.something
}
What is difference between this approaches?
How does it put in memory?
Whether there are underwater rocks when I use first approach with second in the same function? For example, when two arguments passed in same function and first would equal to second and vice versa.
Like that:
name_t* foo(name_t* foo, name_t foo2)
{
//do some changes with structures
foo->something = foo2.something;
return foo;
}
Thanks.
The First version passes a pointer to the caller's structure. Any changes made through the pointer will affect the caller's structure.
The Second version passes a copy of the caller's structure, because C is a call-by-value language. Any changes only affect the local copy, not the caller's structure. However, it's a shallow copy; if the structure contains pointer to other structures, they are not copied recursively, and changes to those referenced structures will affect the originals.
The last example should be fine. foo2
is a copy of the caller's structure, you can make changes to it without affecting the caller. Then you can modify the caller's structure when you assign through the foo
pointer. There's no aliasing problem since one is a copy.