[solved] const char* to char[]

Hello everyone,

I noticed a strange behaviour of a function of mine

main.cpp

#include <Arduino.h>

#include "MyObject.h"

Child child = Child(2,"abcde1245");
// Child child1 = Child(3,"abcdef");


void setup() {

  Serial.begin(9600);

  Serial.println(child.getName());
  // Serial.println(child1.getName());

  delay(500);
}

void loop() {
    // Serial.println("Loop");


    // delay(1000);

}

MyObject.h

class MyObject {

  uint16_t ID = 0;
  char XN[9] = {0};
  uint16_t SIZE = 0;
public:

  MyObject(uint16_t id, const char* name) {
    ID = id;
    // SIZE = size;
    memcpy(XN,name,sizeof(XN));
  }

  const char* getName() {
    // Serial.print("size "); Serial.println(sizeof(XN));
    return XN;
  }
};

class Child : public MyObject {
public:
  Child(uint16_t id,const char* name) : MyObject(id,name) {

  }


};

Sometimes the char array NAME is not written correctly and the result looks like

output:

pm.sm1␁␁

which should just read 'pm.sm1'.

After activating the Serial.print() function in the method getName() the function behaves normal. Does the Serial.print function changes the access to my array? Or can I not fill my char array using memcpy?

Thanks for the help

You forgot about a terminating null character.

Child child = Child(2,"abcde1245");
  char XN[9] = {0};

Is there room in a 9 character array for 9 characters and a terminating '\0' ?

char XN[9] = {0};

This will hold only 8 characters plus the terminating zero. "abcde1245" is 9 characters.

Of course!

That was really embarrassing...

Thanks a lot