-5

Here is C++ code:

void Foo(char* k, struct_t* &Root) 

how to implement it in pure C?

Artbaby
  • 3
  • 3
  • Why don't you simply send a pointer's pointer? – PlamZ Jan 19 '15 at 18:34
  • 1
    what are you trying to achieve? – Iharob Al Asimi Jan 19 '15 at 18:35
  • 5
    so pass a pointer to the variable, and there's your "reference" – Marc B Jan 19 '15 at 18:35
  • Behind the scene references are fundamentally pointers, the only difference is that the language doesn't tolerate `null` references and you don't have to use pointer-specific syntax to handle them. As C doesn't support references, use pointers instead. Since your referenced variable is also a pointer, use pointer to pointer, as `struct struct_t** Root`. – Havenard Jan 19 '15 at 18:40
  • http://stackoverflow.com/questions/2229498/passing-by-reference-in-c – bolov Jan 19 '15 at 19:41

1 Answers1

1

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.

Spencer D
  • 3,376
  • 2
  • 27
  • 43