Need some help passing arrays

Status
Not open for further replies.

KrisKasprzak

Well-known member
I've got a program where i'm trying to pass an array to a function, then print an element from that passed array. It only prints element 0.

I believe it has to do with pointers--which i really don't understand.

The attached code prints this (notice the missing element 1

start
Black
White
Up
Down
Sensor
Source
End
Black

Up

Sensor


Any help greatly appreciated.

Code:
const char *InvertText[2][3] = {{"Black"}, {"White"}};
const char *OrientationText[2][4] = {{"Up"}, {"Down"}};
const char *VoltInputText[2][6] = {{"Sensor"}, {"Source"}};


void setup() {

  Serial.begin(9600);

  delay(1000);
  // this works
  Serial.println("start");
  Serial.println(*InvertText[0]);
  Serial.println(*InvertText[1]);
  Serial.println(*OrientationText[0]);
  Serial.println(*OrientationText[1]);
  Serial.println(*VoltInputText[0]);
  Serial.println(*VoltInputText[1]);
  Serial.println("End");

}

  void loop() {

    DumpText(*InvertText);
    DumpText(*OrientationText);
    DumpText(*VoltInputText);
    while(1){}
  }

  void DumpText(const char *myarray[]) {

    // only element 0 prints
    Serial.println(myarray[0]);
    Serial.println(myarray[1]);
   

  }
 
You are creating 2D arrays, probably not what you wanted. You are passing an array row to DumpText, the second element of which is a nullptr.

What you probably want is:
Code:
const char* InvertText[2] = {"Black", "White"};
const char* OrientationText[2] = {"Up", "Down"};
const char* VoltInputText[2] = {"Sensor", "Source"};

void setup() {
    Serial.begin(9600);
    
    delay(1000);
    // this works
    Serial.println("start");
    Serial.println(InvertText[0]);
    Serial.println(InvertText[1]);
    Serial.println(OrientationText[0]);
    Serial.println(OrientationText[1]);
    Serial.println(VoltInputText[0]);
    Serial.println(VoltInputText[1]);
    Serial.println("End");
}

void loop() {
    DumpText(InvertText);
    DumpText(OrientationText);
    DumpText(VoltInputText);
    while(1){}
}

void DumpText(const char* myarray[]) {
    // only element 0 prints
    Serial.println(myarray[0]);
    Serial.println(myarray[1]);
}
 
Status
Not open for further replies.
Back
Top