2

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.

UmNyobe
  • 22,539
  • 9
  • 61
  • 90
dare2k
  • 417
  • 2
  • 8
  • 24

5 Answers5

9

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;
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
3
countinfunc(uint8_t *readCount)
{
 uint8_t i;
 i = *readCount;
 ....
}
MOHAMED
  • 41,599
  • 58
  • 163
  • 268
3

replace

i = readCount;

with

i = *readCount;
Bhavik Shah
  • 5,125
  • 3
  • 23
  • 40
2

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

i = *readCount;

and you'll be fine.

Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55
1

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

Community
  • 1
  • 1
Omkant
  • 9,018
  • 8
  • 39
  • 59