C 通过引用传递变量 [英] C passing variable by reference

查看:65
本文介绍了C 通过引用传递变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

main()
{
 uint8_t readCount;
 readCount=0;
 countinfunc(&readCount);
}

countinfunc(uint8_t *readCount)
{
 uint8_t i;
 i = readCount;
 ....
}

问题在于,当它进入函数时,变量i在赋值后的值与0不同.

Problem is that when it enters in the function the variable i has a different value then 0 after the assignment.

推荐答案

这是因为在 countinfunc 中,变量是一个 指针.您必须使用指针取消引用运算符才能在函数中访问它:

It's because in countinfunc the variable is a pointer. You have to use the pointer dereference operator to access it in the function:

i = *readCount;

将变量作为函数的引用传递的唯一原因是,如果它是一些可能复制成本很高的大数据,或者当您想在函数内部设置它的值时,它在离开函数时保留该值.

The only reason to pass a variable as a reference to a function is if it's either some big data that may be expensive to copy, or when you want to set it's value inside the function to it keeps the value when leaving the function.

如果要设置值,请再次使用解引用运算符:

If you want to set the value, you use the dereferencing operator again:

*readCount = someValue;

这篇关于C 通过引用传递变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆