Assuming your code is otherwise correct:
I think it would help you to understand how NSLog
and other printf-style functions work. When you call NSLog(@"%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:
- Apply a cast:
NSLog(@"cell.x: %i", (int)cell.x);
- Leave it a float but use the format string to hide the decimals:
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 = 0
and is never changed. So you assign values to:
pathCells[0][0].x = pCLocation.x;
pathCells[0][0].y = pCLocation.y;
cellCount[0]++;
Then you print:
pathCells[0][cellCount[-1]].x
pathCells[0][cellCount[0]].y
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 address foo
plus offset bar
. 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
, and counter
are and how they relate to each other. I think you have a bug in how you are combining these things.