I want to create a wrapper for printing statements, to make sure that the EOL-character is set (and only once!), and I want to be able to call this function directly with a string literal or with a char array - like normal print statements.
The check is if the last character matches the specified EOL-char. If not, it is added with strcat. The minimal example below does not work as expected though. When calling the function with a string literal the string is printed twice, i.e. "String literal\nString literal" (see full output below).
I know the behaviour is different between a char array and string literal, because the latter is not automatically null-terminated if sent as argument. That's why I added the null-terminator after strncpy.
If I replace '&EOL' by simply "\n", it works fine, but that of course defies the purpose of having the general EOL.
Can someone explain this behaviour, and how should I fix it?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
#include <stdio.h>
const char EOL = '\n';
int main()
{
char txt[] = "Hello World";
msgSend("String literal");
msgSend(txt);
return 0;
}
void msgSend(const char *msg) {
char out[65];
strncpy(out, msg, strlen(msg));
out[strlen(msg)] = '\0';
printf("Output message is %i chars long.\n", strlen(out));
if (out[strlen(out)-1] != EOL) strcat(out, &EOL);
printf("Output message is now %i chars long.\n", strlen(out));
printf(out);
}
|
The output:
1 2 3 4 5 6 7
|
Output message is 14 chars long.
Output message is now 29 chars long.
String literal
String literalOutput message is 11 chars long.
Output message is now 26 chars long.
Hello World
String literal
|