开发者

2D Pointer initialization

开发者 https://www.devze.com 2023-03-15 07:36 出处:网络
How to initialize a 2D array with pointer. int *mapTable[] = { {1,10} , {2,20} , {3,30} , {4,40} };// It\'s giv开发者_运维百科ing error

How to initialize a 2D array with pointer.

int *mapTable[] = { {1,10} , {2,20} , {3,30} , {4,40} };  // It's giv开发者_运维百科ing error

Here int *mapTable is giving an error.

How can I declare them properly?


int *mapTable[] is not a 2D array: it is a 1D array of pointers.

But then you go and use a 2D array initialiser { {1,10} , {2,20} , {3,30} , {4,40} }.

That's why it's "giving error".


The 2D array way

Try:

int mapTable[][2] = { {1,10} , {2,20} , {3,30} , {4,40} };

And, yes, you do need to specify the size of that second dimension.


The 1D array of pointers way

This is a little more involved, and is usually too complex to be worth it.

It also usually requires dynamic allocation, causing a total mess with object lifetime:

int *mapTable[] = { new int[2], new int[2], new int[2], new int[2] };

int main() {
   mapTable[0][0] = 1; mapTable[0][1] = 10;
   mapTable[1][0] = 2; mapTable[1][1] = 20;
   mapTable[2][0] = 3; mapTable[2][1] = 30;
   mapTable[3][0] = 4; mapTable[3][1] = 40;

   // then, at the end of your program:
   for (size_t i = 0; i < 4; i++)
      delete[] mapTable[i];
}

As you can see, this is not ideal.

You can avoid dynamic allocation:

int mapTable0[] = {1,10};
int mapTable1[] = {2,20};
int mapTable2[] = {3,30};
int mapTable3[] = {4,40};
int *mapTable[] = { &mapTable0[0], &mapTable1[0], &mapTable2[0], &mapTable3[0] };

But I'm not sure why you'd want to go down this avenue.


The questin is tagged C++ and C; but all these answers only cover C++ (for the pointer way).

So in C, you can declare the rows separately and then compose them.

int r0[] = {1,10}, r1[] = {2,20}, r2[] = {3,30}, r3[] = {4,40};
int *mapTable[] = { r0, r1, r2, r3 };

Or, using C99, you can make anonymous arrays in the initializer.

int *mapTable[] = { (int[]){1,10}, (int[]){2,20}, (int[]){3,30}, (int[]){4,40} };

Both of these use the fact that an array reference decays into a pointer.

0

精彩评论

暂无评论...
验证码 换一张
取 消