views:

32

answers:

1

I want to pass a struct within a method so i can change it's value within, but I am not too sure on it's syntax:

 struct qsTracker {
          int points;
          BOOL flagged;
 } myCurrentQs;

[self calculateScore:myCurentQs];

-(void) calculateScore:(struct qsTracker) currentQs  {
    currentQs.points++;
    currentQS.flagged = YES;
}

Obviously, currentQs doesn't see any changes. any help would be much appreciated.

+4  A: 

You should pass in a pointer to the struct, instead of the struct itself:

-(void) calculateScore:(struct qsTracker *) currentQs  {
    currentQs->points++;
    currentQS->flagged = YES;
}

And then:

[self calculateScore:&myCurentQs];

Because currentQs is now a pointer, changes made inside the method will be reflected outside the method.

mipadi
thx it worked, i tried this method earlier but i was using currentQs.points++; rather than currentQs->points why is that?
Frank
The `.` operator works on values (the struct itself), whereas the `->` first dereferences a pointer, and then works on a field in that structure. Basically, `currentQs->points` is synonymous with `(*currentQs).points`.
mipadi