gpt4 book ai didi

c++ - 如何将使用 C++ 传递引用的函数转换为 C?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:05:09 25 4
gpt4 key购买 nike

我有一段用 C++ 编写的代码,需要用 C 编写。我转换了大部分代码,但我不知道如何将函数中的 C++ 传递引用转换为 C 代码,即

例子:

int& a;

它在某些函数中用作输入变量:

void do_something(float f, char ch, int& a)

当我用 C 编译它时,出现编译器错误。在 C 中替换引用传递的正确方法是什么?

最佳答案

在 C 中实现这一点的方法是通过指针传递:

void do_something(float f, char ch, int* a)

还有在 do_something 中使用 a 而不是

void do_something(float f, char ch, int& a)
{
a = 5;
printf("%d", a);
}

您现在需要取消引用 a

void do_something(float f, char ch, int* a)
{
*a = 5;
printf("%d", *a);
}

当调用 do_something 时,您需要获取传递给 a 的内容的地址,而不是

int foo = 0;
d_something(0.0, 'z', foo);

你需要做的:

int foo = 0;
d_something(0.0, 'z', &foo);

获取 foo 的地址(即指针)。

关于c++ - 如何将使用 C++ 传递引用的函数转换为 C?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7517625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com