0

I have different arrays of different sizes, and a list of pointers to the addresses of each array. How do I select each array using the list of pointers, and access it's elements. On Teensy 3.2 board.

int * arr_list[3];        
const int arr_sizes[3] = {3,4,5};  // array of the array sizes
const int ar1[3] = {12,2,8};       // arrays of  different sizes
const int ar2[4] = {41,3,6,47};
const int ar3[5] = {9,32,1,5,7}; 

void map_arrays(){          // list of pointers with the addresses of the 
                            // arrays
arr_list[0] = (int*) &ar1;  
arr_list[1] = (int*) &ar2;
arr_list[2] = (int*) &ar3;
}; 

int arr_number = 1;          // select array 
int a = arr_sizes[arr_number];    // the size of the selected array
int *b = arr_list[arr_number];  
int test = 0;

void setup() {

Serial.begin(57600);  //serial monitor 

} 

void loop() {

for (int i=0; i<a; i++) {     // for the selected arr_number iterate and
test = b[i];                  // return the index elements 

}

Serial.println("size =");      
Serial.println(a);
Serial.println();
delay(1000);
Serial.println("index =");     
Serial.println(test);
Serial.println();
delay(500);

 }
0

You have it right, only fix initialization of test variables:

  1. you do not call map_arrays() in setup()
  2. you assign uninitialized arr_list item to b
const int* arr_list[3];
const int arr_sizes[3] = { 3, 4, 5 };  // array of the array sizes
const int ar1[3] = { 12, 2, 8 };       // arrays of  different sizes
const int ar2[4] = { 41, 3, 6, 47 };
const int ar3[5] = { 9, 32, 1, 5, 7 };

void map_arrays() {          // list of pointers with the addresses of the
// arrays
  arr_list[0] = ar1;
  arr_list[1] = ar2;
  arr_list[2] = ar3;
}

int arr_number = 1;          // select array
int a = arr_sizes[arr_number];    // the size of the selected array
const int *b;
int test = 0;

void setup() {

  Serial.begin(57600);  //serial monitor

  map_arrays();

  b = arr_list[arr_number];

  for (int i = 0; i < a; i++) {     // for the selected arr_number iterate and
    test = b[i];                 // return the index elements
    Serial.println(test);
  }

  Serial.println("size =");
  Serial.println(a);
  Serial.println();
  delay(1000);
  Serial.println("index =");
  Serial.println(test);
  Serial.println();
  delay(500);

}

void loop() {
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.