Home > Software engineering >  How to convert a char* to a char array
How to convert a char* to a char array

Time:12-20

I'm receiving some data over serial of variable names and values in char. The variable name gets stored in an array pointed to by the char*. I'm trying to compare the char array data I received, to several other char arrays so I can determine which variable I have received data for.

How can I convert the char* to a char array, so I can compare it to other arrays, for example by using the strcmp function?

Basically the serial data gets fed into an array and processed by this function:

void process(char *message) {
  char *name = strsep(&message, " ");  // split at the space
  if (!message) {
    Serial.println("Error: no value given");
    return;
  }
  char *endp;  // end of the numeric value
  long value = strtol(message, &endp, 0);
  if (endp == message) {
    Serial.println("Error: could not parse value");
    return;
  }
  // Successfully parsed.
  char namestr[] = name;
  if (strcmp(&namestr, &var1str) == 0) {
    Serial.print(name);
    Serial.print(" received value ");
    Serial.println(value);
  }
}

However, when I try char namestr[] = name; I get the following error: initializer fails to determine size of 'namestr'

CodePudding user response:

As @stark mentioned in comment, you just can pass name to the strcmp() function. A char array is internally just a char pointer char *

  • Related