C 不支持通过引用传递变量.怎么做

C does not support passing a variable by reference. How to do it?

本文关键字:变量 不支持 引用      更新时间:2023-10-16

这是C++代码:

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

如何在纯C中实现它?

你是对的,C 不支持通过引用传递(因为它是由 C++ 定义的)。但是,C 支持传递指针。

从根本上说,指针是引用。指针是存储变量可以定位的内存地址的变量。因此,标准指针C++引用相当。

所以在您的情况下,void Foo(char *k, struct_t* &Root)类似于 void Foo(char *k, struct_t **Root) .要访问Foo函数中的Root结构,您可以这样说:

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;
}

因此,仅传递指针等效于传递引用。