How to use a c-type array as an ivar?
I need a good old-fashioned 2-dim开发者_如何学Censional array of integers in my program, but no matter how I try to declare it as an ivar, and then use @property/@synthesize, I get one compiler complaint or another.
I declare
int spotLocations[10] [10]
as an ivar.
That much works, but then the @property/@synthesize process never passes muster.
You can't do this. Array variabless can never be lvalues in C, which means you can never declare a function that returns an array, because it would be impossible to assign the result of the function to an array variable (since it can't be an lvalue).
Properties are just a shorthand way of declaring a function that returns a type. Since functions can never return arrays, you can never declare a property that is an array.
If you absolutely need to move matrices around like this, you could wrap it in a struct, which can be lvalues:
typedef struct {
int value[10][10];
} matrix;
...
@property matrix spotLocations;
Of course, accessing the locations is a little more convoluted, you have to use
spotLocations.value[x][y]
Declare the instance variable as a pointer and then dynamically create the array in your init method. Use the assign parameter for the @property declaration.
Allocation:
spotLocations = malloc(100 * sizeof(int));
Access a column and row by doing:
int aValue = spotLocations[x + y * 10];
Remember to free() the pointer when you're done with it.
精彩评论