C passing variable by reference

17,004

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

Solution 2

replace

i = readCount;

with

i = *readCount;

Solution 3

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

Solution 4

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

i = *readCount;

and you'll be fine.

Solution 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

Share:
17,004
dare2k
Author by

dare2k

Updated on June 04, 2022

Comments

  • dare2k
    dare2k almost 2 years

    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.

  • dare2k
    dare2k over 11 years
    I can't believe I didn't try that.