Passing string to class-method and store it in property

Hello everyone,

this might be a quite simple question but I don’t get the problem.

I have this class:

class sensor {

  public:
  void setUnit(char unitValue[ ]) {
    unit = unitValue;
  }
  
  private:
  char unit[ ]; // Einheit des gemessenen Wertes
};

Trying to compile this just throws this error:

/tmp/990059934/200119_Growbox/200119_Growbox.ino: In member function 'void sensor::setUnit(char*)':

/tmp/990059934/200119_Growbox/200119_Growbox.ino:161:11: error: invalid use of array with unspecified bounds

unit = unitValue;

Could please anyone tell me why this isn’t working and how I can store a string in the property “unit”?

Thanks!

You must specify the size of the unit array.

Next time, post a complete code so we can copy / paste into the Arduino IDE and see the exact error that you see.

Okay, I tried this:

class sensor{
  
  public:
  void setUnit(char unitValue[]) {
    unit = unitValue;
  }
  
  private:
  char unit[10];
  
};

void setup() {
    sensor sensor;
    sensor.setUnit("myUnit");
}

void loop() {
    
}

and got this error message:

/tmp/498138925/sketch_jan20a/sketch_jan20a.ino: In member function 'void sensor::setUnit(char*)':

/tmp/498138925/sketch_jan20a/sketch_jan20a.ino:5:12: error: incompatible types in assignment of 'char*' to 'char [10]'

exit status 1

What am I doing wrong?

And what if I don't know the size yet - don't I waste memory if I would specify the lenght to let's say 100 but only use 20 characters?

You can’t assign array contents that way. Is the array a proper (null-terminated) c-string? If so, you can use strcpy. Or, the safer strncpy.

If not, you can pass the number of elements as a parameter and use memcpy. Be sure to confirm the length is less than or equal to your class’s array size.

If you don’t want to set the array size at compile time, you can make the class member a pointer (char *) and use dynamic allocation. But, that will cause memory fragmentation problems on a limited-RAM processor if you’re not careful.