简体   繁体   中英

Allocating memory for a 3D array

I have the array: char game[10][10][3] , and I want to allocate memory for the [10][10], how should I do it? I thought in something like char **game[3] , but when I do some malloc, it says that I need to inicialize the array.

It's pretty easy to allocate:

 typedef char game_board[10][10][3];

 game_board* board = malloc(sizeof(game_board));

Though honestly just using it without pointers will be a lot less messy.

Remember that char **game[3] is a pointer to a pointer to an array of size 3. Note the intermediate pointer. In the original definition it's an array of 10 array of 10 arrays of length 3. There is no pointers in this structure. While both forms can be referenced like game[x][y][z] that is only because of how C has made the syntax identical. It's not a reflection on the actual structure involved.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM