'About string, null character and strcmp
I created C program in microcontroller, and want to compare string in my C program with string that received from my PC, my program in PC using C#, and by default string in C# doesn't contain null character.
So, my c program doesn't automatically add null character in string that received from PC?
And does strcmp function can compare 2 strings, 1 string contain null character, and another one not contain null character?
Solution 1:[1]
Defination of Strings in C (from Wikipedia) is
A string is a contiguous sequence of code units terminated by the first zero code (corresponding to the ASCII null character).
That said, without NUL character, you cannot use standard string functions like strcmp() or strcpy() and may end up corrupting memory.
You can do two things:
Add Char.MinValue at the end of string in your C# code before transmitting.
string str = "Hello,World!" + Char.MinValue; // Add NUL.
Or you can write your own string compare function like
int myStrcmp(char* str1, char* str2, int len)
{
int retVal = 0,
for(int loopcnt = 0; loopcnt < len; loopcnt++)
{
if((*str1) > (*str2))
{
retVal = -1;
break;
}
else if((*str1) < (*str2))
{
retVal = 1;
break;
}
str1++;
str2++;
}
return retVal;
}
But then, you will require length of string. If you already know the length, it's better and faster to add a NUL character manually. :-)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | The Paramagnetic Croissant |
