C passing variable by reference [closed]

雨燕双飞 提交于 2019-12-11 01:06:21

问题


I have the following code:

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

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

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


回答1:


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;



回答2:


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



回答3:


replace

i = readCount;

with

i = *readCount;



回答4:


You're setting i to the address of readCount. Change the assignment to:

i = *readCount;

and you'll be fine.




回答5:


just replace

i=readCount by i=*readCount

You cannot assign (uint8_t *) to uint8_t

For more on this here is the link below Passing by reference in C



来源:https://stackoverflow.com/questions/13069337/c-passing-variable-by-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!