问题
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