Multi-dimensional arrays with different number of elements

Maybe you can elaborate what "wrong code" means. If I replace X by 5, the code happily compiles.

If you really want the first dimension to be of different sizes, you first need to define a number of arrays like

int pin1[] = {1, 1};
int pin2[] = {2, 2, 2, 2, 2};
int pin3[] = {3, 3};

and next you can use an array of pointers

int *pinMatrix[]=
{
  pin1,
  pin2,
  pin3,
};

This however brings another problem; in pinMatrix you can't determine the size of the individual arrays. So a two-dimensional iteration is doomed to fail.

To solve that, you can use an array of structs; the struct combines a pointer to the pinX with the number of elements in pinX.

struct PINS
{
  int *pins;
  uint16_t numElements;
};

PINS pinMatrix[] =
{
  {pin1, sizeof(pin1) / sizeof(pin1[0])},
  {pin2, sizeof(pin2) / sizeof(pin2[0])},
  {pin3, sizeof(pin3) / sizeof(pin3[0])},
};

Instead of typing stuff like sizeof(pin1) / sizeof(pin1[0]) all the time, you can define a macro and place it at the top of the code

#define NUMELEMENTS(x) (sizeof(x) / sizeof(x[0]))

The below code demonstrates how to iterate the two dimensions

#define NUMELEMENTS(x) (sizeof(x) / sizeof(x[0]))

int pin1[] = {1, 2};
int pin2[] = {9, 8, 7, 6, 5};
int pin3[] = {3, 4};

struct PINS
{
  int *pins;
  uint16_t numElements;
};

PINS pinMatrix[] =
{
  {pin1, NUMELEMENTS(pin1)},
  {pin2, NUMELEMENTS(pin2)},
  {pin3, NUMELEMENTS(pin3)},
};

void setup()
{

  Serial.begin(57600);
  Serial.print("number of rows in pinMatrix = "); Serial.println(NUMELEMENTS(pinMatrix));
  Serial.println();

  for (uint16_t rowCnt = 0; rowCnt < NUMELEMENTS(pinMatrix); rowCnt++)
  {
    Serial.print("number of columns in pinMatrix["); Serial.print(rowCnt);
    Serial.print("] = "); Serial.println(pinMatrix[rowCnt].numElements);
    Serial.print("content = ");
    for (uint16_t colCnt = 0; colCnt < pinMatrix[rowCnt].numElements; colCnt++)
    {
      Serial.print(pinMatrix[rowCnt].pins[colCnt]); Serial.print(", ");

    }
    Serial.println();
    Serial.println();

  }
}

void loop()
{
  // put your main code here, to run repeatedly:

}
2 Likes