What is the best practice on declaring strings / char arrays in C?
I have the below samples and comments.
Code#1
How to properly declare the below?
char message1[] = "abc"; // will add \0 (null character in the end. so message1 is not equal to message2)
char message2[] = {'a','b','c'}; // tedious to type if you have hundreds of characters to add
Does the recv()
socket function in C adds null terminating character at the end?
Code#2
How to compare message4 to message3 if matched partially?
char message3[] = {'a','b','c','e','f'}
char message4[] = {'a','b'}
Just exploring and new to programming .
Regards
sya
char message1[] = "abc";
is proper and the normal way. The ""
means that a null terminator is added at the end automatically.
char message2[] = {'a','b','c'};
is wrong, this is not a C string since it is not null terminated. You could have included a '\0'
at the end and then it would become be a correctly declared C string.
revc
has nothing to do with strings at all, it works on raw data and knows nothing about strings. It deals with given sizes in bytes.
Normally you compare strings with strcmp
, but in the message3
+message4
case, you don't have strings since they were not null terminated. You could instead compare them as raw data with
memcmp(message3, message4, sizeof(message4))
where it is known that message4
is the smallest one.