Home > other >  How to create an array of arrays in C
How to create an array of arrays in C

Time:01-03

Using plain c, if I have the following two arrays:

WCHAR depthUnits[2][10] = { _T("feet"), _T("metres") };
WCHAR speedUnits[3][10] = { _T("ft/min"), _T("m/min"), _T("m/s") };

How can I create an array called say allUnits and fill it with the above so that it will behave like so:

allUnits[0][0] = "feet";
allUnits[0][1] = "metres";
allUnits[1][0] = "ft/min";
allUnits[1][1] = "m/min";
allUnits[1][2] = "m/s";

So basically allUnits is an array and each element of that array is itself an array such that allUnits[0] references depthUnits and allUnits[1] references speedUnits.

Thanks.

CodePudding user response:

WCHAR *allUnis[2][3];

/* ... */

allUnits[0][0] = depthUnits[0];
allUnits[0][1] = depthUnits[1];
allUnits[1][0] = speedUnits[0];
allUnits[1][1] = speedUnits[1];
allUnits[1][2] = speedUnits[2];

CodePudding user response:

This uses array initialization, maybe that's what you wanted:

#include <stdio.h>

int main(void)
{
  char* allUnits[][3] = {
    {"feet", "meters"},
    {"ft/min", "m/min", "m/sec"}
  };

  printf("0 0: %s\n", allUnits[0][0]);
  printf("0 1: %s\n", allUnits[0][1]);
  printf("1 0: %s\n", allUnits[1][0]);
  printf("1 1: %s\n", allUnits[1][1]);
  printf("1 2: %s\n", allUnits[1][2]);
}

CodePudding user response:

You can initialize an array of arrays like you would any other array.

WCHAR* depthUnits[] = { _T("feet"), _T("metres") };
WCHAR* speedUnits[] = { _T("ft/min"), _T("m/min"), _T("m/s") };
WCHAR** allUnits[] = { depthUnits, speedUnits };
  • Related