I'm getting confused by pointers in objective-c.
Basically I have a bunch of static data in my code.
static int dataSet0[2][2] = {{0, 1}, {2, 3}};
static int dataSet1[2][2] = {{4, 5}, {6, 7}};
And I want to have an array to index it all.
dataSets[0]; //Would give me dataSet0...
What should the type of dataSets be, and how would I initialize it?
Pointers to multi-dimensional arrays can be tricky. A typedef can help:
typedef int (*DataSetType)[2];
DataSetType dataSets[] = { dataSet0, dataSet1 /* and so on*/ };
您可以使用NSPointerArray
。
While it's laid out the same in memory, a pointer to a multidimensional array is different than a pointer to a flat array. The compiler has to convert the [][] index to a flat array index for any multidimensional arrays. Can't mix the two or the distinction for the compiler is lost. You can either use all flat arrays:
static int dataSet00[2] = {0,1};
static int dataSet01[2] = {2,3};
static int * dataSet0[2] = {dataSet00, dataSet01};
static int dataSet10[2] = {4, 5};
static int dataSet11[2] = {6, 7};
static int * dataSet1[2] = {dataSet10, dataSet11};
static int ** dataSets[2] = {dataSet0, dataSet1};
or one big multidimensional array:
static int dataSets[2][2][2] = {{{0,1},{2,3}},{{4,5},{6,7}}};
but not a combination of the two unless you clue the compiler in by declaring a special datatype per Jon's suggestion.
Your index array would be an array of pointers to pointers to int.
So the declaration would look like:
int ** dataset[numOfDataSets] = {dataSet0, dataSet1, ...}
Remember that objective-c is a proper superset of ansi-c, and this question in particular is about the c language, really.
Edit: It's important to remember that in C, arrays are essentially just pointers, and two-dimensional arrays are pointers to pointers.
Edit 2: I think act actually I muffed operator precedence. Should be:
int (** dataset)[numOfDataSets] = {dataSet0, dataSet1, ...}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.