Home > Mobile >  C: How can I create a 2d array that hold 2d arrays?
C: How can I create a 2d array that hold 2d arrays?

Time:02-10

for example I have generated a "zone" of 1s and 0s in a 2x2 2d array . But i need to store 9 of these zones to access whenever from another 3x3 2d array "map". The zone arrays are randomly generated and need to stay the same once added to the 2d map array, so that I could "leave" a zone and come back and itd be the same. Kinda like an ASCII game

such that

int zone[2][2];
// fill zone array
int map[3][3];
map[0][0] = zone;

CodePudding user response:

I think to make it simple you can use struct in c. It will be easier to manage and modify it with struct

#include <stdio.h>

struct Zone {
    int zone[2][2];
};

int main()
{
    struct Zone map[3][3];
    struct Zone zone1;
    int i, j;
    for (i = 0; i < 2; i  ) {
        for (j = 0; j < 2; j  ) {
            zone1.zone[i][j] = i   j; // putting some values for example
        }
    }
    map[0][0] = zone1;
}

CodePudding user response:

You can create a multi-dimensional 9x2x2 array where each 2x2 zone is accessed by their zone index (0-8).

int zone[9][2][2];

// I can now access any of the nine 2x2 zones using indices 0-8
zone[0][0][0]
zone[1][0][0]
zone[2][0][0]
...
zone[8][0][0]
  • Related