0

Still don't understand about char concatenation.

void setup() {

  testCounter(3);

}

void loop() {
  // put your main code here, to run repeatedly:
}

char testCounter(int countx){
  char a[10];
  strcpy(a, "COUNTER: ");
  strcat(a, printDigits(countx));
  return a;
}

char printDigits(int digits){
  char a[3];
  if(digits < 10) {
    strcpy(a, "0");
    sprintf(a,"%d",digits);
  } else {
    sprintf(a,"%d",digits);
  }
  return a;
}

Error: invalid conversion from 'char' to 'const char' [-fpermissive]* in testCounter line:

strcat(a, printDigits(countx));

Don't understand this part of error.

printDigits function return char, so... strcat should be work. But why still error?

Please help...

1 Answer 1

2
char printDigits(int digits){

You are telling the compiler you will return one character.

 char a[3];

a is three characters. Thus the declaration doesn't match.


You could change the declaration to:

char * printDigits(int digits){

But even that would be bad because a would go out of scope after the function returns.


 char a[3];

That's a little short for putting an integer into. An integer might be 5 characters, plus possibly a minus sign, and you need a trailing "null" at the end. Seven bytes would be safer.


The simplest way of doing what you seem to be wanting is:

void setup() {
  Serial.begin (115200);
  testCounter(3);
}

void loop() {
}

char testCounter(int countx){
  char a[15];
  sprintf (a, "COUNTER: %02d", countx);
  Serial.println (a);
}

Also, here:

  if(digits < 10) {
    strcpy(a, "0");
    sprintf(a,"%d",digits);
  } else {

That won't work because you are putting "0" into a and then overwriting it with sprintf.


printDigits function return char, so... strcat should be work. But why still error?

Look at the prototype for strcat:

http://www.cplusplus.com/reference/cstring/strcat/

It expects char * not char. They are different things. One is a pointer, one isn't.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.