print with char array on heap

Hello, I want to declare a large char (byte) array on the heap then print this to serial

I tried this

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

   char *buffer;
   int i = 0;
   buffer = (char*) malloc(20);
   if (buffer == NULL) Serial.println("sh!t hit the fan");
   
   for( i = 0; i < 19; i++) {
      buffer[i] = i; 
   }
   buffer[i] = 0;
   Serial.println("before");
    Serial.print(*buffer);
    Serial.println("after");
    delay(1000);
    free(buffer);
}

But all that comes out is

"before
after"

(space between the newline and after). What have I done wrong?

Thanks

You have two problems.

  • you are not filling the array with printable characters
    Try this:
      buffer[i] = i + 'A';
  • you are printing only the first character in the array - not the string as a whole. Try this:
    Serial.print(buffer);

Pete

That was straight forward - I should of added 65. Doh - I actually did this just the other day with another MCU.

Excuse me on the second one, I was trying various permutations to see why it didn't work and left that in (pointer decay) - i knew that shouldn't work anyway... honest :blush:

Time for bed.

Many thanks :slight_smile: