You’re right, C does not support passing by reference (as it is defined by C++). However, C supports passing pointers.
Fundamentally, pointers are references. Pointers are variables which store the memory address at which a variable can be located. Thus, standard pointers are comparable C++ references.
So in your case, void Foo(char *k, struct_t* &Root)
would be similar to void Foo(char *k, struct_t **Root)
. To access the Root
structure within the Foo
function, you could then say something like:
void Foo(char *k, struct_t **Root){
// Retrieve a local copy of the 1st pointer level
struct_t *ptrRoot = *Root;
// Now we can access the variables like normal
// Perhaps the root structure contains an integer variable:
int intVariable = ptrRoot->SomeIntegerVariable;
int modRootVariable = doSomeCalculation(intVariable);
// Perhaps we want to reassign it then:
ptrRoot->SomeIntegerVariable = modRootVariable;
}
Thus, just passing pointers is equivalent to passing a reference.
solved C does not support passing a variable by reference. How to do it?