I am having difficulty understanding why the following code is giving me the numbers below. Can anyone explain this conversion from float to int? (pCLocation is a CGPoint)
counter = 0;
pathCells[counter][0].x = pCLocation.x;
pathCells[counter][0].y = pCLocation.y;
cellCount[counter]++;
NSLog(@"%@",[NSString stringWithFormat:@"pCLocation at:
%f,%f",pCLocation.x,pCLocation.y]);
NSLog(@"%@",[NSString stringWithFormat:@"path cell 0: %i,%i",
pathCells[counter][cellCount[counter-1]].x,pathCells[counter][cellCount[counter]].y]);
2012-03-09 01:17:37.165 50LevelsBeta1[1704:207] pCLocation at: 47.000000,16.000000
2012-03-09 01:17:37.172 50LevelsBeta1[1704:207] path cell 0: 0,1078427648
Assuming your code is otherwise correct:
I think it would help you to understand how
NSLogand other printf-style functions work. When you callNSLog(@"%c %f", a_char, a_float), your code pushes the format string and values onto the stack, then jumps to the start of that function’s code. Since NSLog accepts a variable number of arguments, it doesn’t know how much to pop off the stack yet. It knows at least there is a format string, so it pops that off and begins to scan it. When it finds a format specifier%c, it knows to pop one byte off the stack and print that value. Then it finds%f, so now it knows to pop another 32 bits and print that as a floating point value. Then it reaches the end of the format string, so it’s done.Now here’s the kicker: if you lie to NSLog and tell it you are providing a int but actually provide a float, it has no way to know you are lying. It simply assumes you are telling the truth and prints whatever bits it finds in memory however you asked it to be printed.
That’s why you are seeing weird values: you are printing a floating point value as though it were an int. If you really want an int value, you should either:
NSLog(@"cell.x: %i", (int)cell.x);NSLog(@"cell.x: %.0f", cell.x);(Alternate theory, still potentially useful.)
You might be printing out the contents of uninitialized memory.
In the code you’ve given,
counter = 0and is never changed. So you assign values to:Then you print:
I’m pretty sure that
cellCount[-1]isn’t what you want. C allows this because even though you think of it as working with an array of a specific size,foo[bar]really just means grab the value at memory addressfooplus offsetbar. So an index of -1 just means take one step back. That’s why you don’t get a warning or error, just junk data.You should clarify what
pathCells,cellCount, andcounterare and how they relate to each other. I think you have a bug in how you are combining these things.