0

Question given in the title. I'm trying to dynamically allocate the size of an array on runtime on an arduino pro micro. I've tried realloc, malloc and the c++ variant delete and new without success. This is my current test code:

int* test = 0;

void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.println("test");
  if(test != 0){ //c++ delete and new attempt
    delete [] test;
  }
  test = new int[2];
  //test = (int*) realloc(test, 2 * sizeof(int)); //realloc attempt
  //test = (int*) malloc(2*sizeof(int));          //malloc attempt
  test[0] = 1;
  test[1] = 2;
  int answer = test[0] + test[1];
  Serial.println(" " + answer);
  Serial.print(" " + test[0]);
  Serial.println(" " + test[1]);
  Serial.println("test");
  delay(100000000000);
}

All of my attempts result in either some garbage in the serial or in most cases:

test


test

Does anyone know what I'm doing wrong?

1

serial.println doesn't work that way. Or more precisely + with string literal and an int does not create a concatenated string. Instead it treats the string literal as a char* and then does pointer arithmetic on it.

  Serial.print(" ");
  Serial.println(answer);
  Serial.print(" ");
  Serial.print(test[0]);
  Serial.print(" ");
  Serial.println(test[1]);
  Serial.println("test");
  delay(100000000000);
2

This works:

int* test = 0;

void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.println("test");
  if(test != 0){ //c++ delete and new attempt
    delete [] test;
  }
  test = new int[2];
  //test = (int*) realloc(test, 2 * sizeof(int)); //realloc attempt
  //test = (int*) malloc(2*sizeof(int));          //malloc attempt
  test[0] = 1;
  test[1] = 2;
  int answer = test[0] + test[1];
  Serial.println(answer);
  Serial.print(test[0]);
  Serial.println(test[1]);
  Serial.println("test");
  delay(100000000000);
}

In C/C++, you can't add/concatenate Strings and int.

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.