Strcmp error for char[]

Hi

I have some problems with strcmp() function.
I declare and defind my variables like this. rxBuffer is the UDP.read() buffer that I use.

unsigned char udpWord[] = {“Spark”};
unsigned char rxBuffer[10];

Then my strcmp() looks likt this:

if (strcmp(rxBuffer, udpWord) == 0) {
}

But then the online IDE complain:

udp.cpp: In function ‘void loop()’:
udp.cpp:34:33: error: invalid conversion from ‘unsigned char*’ to ‘const char*’ [-fpermissive]
// Check if data has been received
^
In file included from /opt/gcc_arm/arm-none-eabi/include/stdlib.h:11:0,
from …/…/core-common-lib/CC3000_Host_Driver/cc3000_common.h:43,
from …/…/core-common-lib/SPARK_Firmware_Driver/inc/hw_config.h:35,
from …/inc/main.h:37,
from …/inc/spark_utilities.h:30,
from …/inc/spark_wiring.h:33,
from …/inc/application.h:29,
from udp.cpp:3:
/opt/gcc_arm/arm-none-eabi/include/string.h:28:6: error: initializing argument 1 of ‘int strcmp(const char*, const char*)’ [-fpermissive]

I need to write like this instead to get it to work:

if (strcmp(**(char*)**rxBuffer, *(char)**udpWord) == 0) {
}

So, why it it like this? Isn’t char[] already a pointer?
If I don’t remember wrong I have manage strcmp() to work as a first wrote in Keil MDK-ARM.

Will this help? string.compareTo(string2)

http://docs.spark.io/firmware/#string-class-compareto

I think @mdma might be able to comment on this. Maybe the way strings or variables are currently defined in the firmware is affecting the interaction. :wink:

It is because you are using unsigned char instead regular signed char. You can cast as you are doing or switch to memcmp() which takes two pointers and a length.

@kennethlimcp this is the “other” kind of the string–the standard C-style char array, so the Arduino String object is not the way here.

1 Like

Please change the definition to

const char udpWord[] = {"Spark"};
char rxBuffer[10];

As you see, the static string “spark” is a constant, so must be declared const, and strcmp works with regular chars only, not unsigned chars.

Hope that helps!

2 Likes

Tanks @bko and @mdma for your help!
Off cause it should be an char and not unsigned one… :smiley:
I also changed updWord[] to a const…

Now it´s working!

1 Like

Strictly speaking the {} brackets ought not be used. I know it works, in this instance, but it should be either of these:

char x[] = "Spark"; // initialise string (i.e. nul-terminated array of char)
char x[][6] = {"Spark"}; // initialise 1st element of array of 5-char strings (i.e. an array of nul-terminated arrays of char)

The compiler is forgiving, but need not be. This is all legal, and regular syntax:

char x[] = "Spark";
char s[] = {'S','p','a','r','k','\0'}; // single quotes, explicit nul-termination
char *xx[] = {"Spark"};
char *yy[] = {"Spark","Core"};
char zz[][10] = {"Spark","Core","rocks"};

int main() {
        puts(x);
        puts(*xx);
        puts(xx[0]);
        puts(yy[1]);
        puts(zz[2]);
}