How to pass a char-array as parameter to function without pointer / reference

Hey guys,

I'd like to store the name of the control in the object but I want to copy the value and not only send the address of it.

class control {
  public:
    control(char controlName[10]) {
    name = controlName; // Error: incompatible types in assignment of 'char*' to 'char [10]'
  }

  private:
  char name[10];
  //char* name;
};

void setup() {
  control humidityControl("humidityControl");
  
}

void loop() {
  
}

How can I do this / what am I doing wrong / am I misunderstanding?

Many thanks in advance and best regards
Stefan

Use strcpy() to copy the content.

...
  control(const char* inControlName)
  {
    strcpy(name, inControlName);
  }
...

Be aware that your current name array is not big enough to hold "humidityControl".

Something like this might do the job for you. MAKE SURE the LENGTH of the cstring you are passing is NOT greater that name! "humidityControl" is more that 10 characters!

class control {
public:
  control(char *controlName) {
    char i=0;
    
    do{
        name[i] = controlName[i];
        ++i;
    }while(controlName[i]!=0); //since a cstring is always null terminated.
    
    name[i] = 0;
  }

private:
  char name[20]; //increased the array size!
  
};

void setup() {
  control humidityControl((char*)"humidityControl"); //casting of string for good measure! ;)
  
}

void loop() {
  
}

Hope that helps....

ps: @arduino_new beat me to it :smiley:

Both solutions work, thanks guys! Which one is "better" (more efficient, faster, more stable, future-proof, ...)?

alve89:
Both solutions work, thanks guys! Which one is "better" (more efficient, faster, more stable, future-proof, ...)?

The one that uses strncpy.