2
votes

I'm trying to learn more about C and I was wondering if anyone could clarify what's going on here. I'm getting a compiler warning: "warning: assignment makes integer from pointer without a cast @ msg[msglen+1] = "\0""

char *msg = NULL;
int len = 10;
int msglen = 0;

while(<argument>) {

msg = (char *)calloc(len, 1);
strncpy(msg, <some string>, len);
msglen = strlen(msg);
msg[msglen+1] = "\0";

Thanks, I appreciate you help!

3
You're using strncpy(). That's almost certainly not the best solution. - Keith Thompson
msglen = strlen(msg); has potential for undefined behaviour, since strncpy doesn't usually 0-terminate. - Daniel Fischer

3 Answers

2
votes

You are trying to assing a pointer to a string literal to a char. Change the double quotes " for single quotes ' like this:

msg[len - 1] = '\0';

Notice that I changed msglen+1 for len - 1 which indexes the last allocated character.

1
votes

a "\0" is treated as a constant string, and the address to that string is slapped into place when you try to do msg[len - 1] = "\0" hence you get the message "converts..."

do this instead msg[len - 1] = '\0'

0
votes
msg = malloc(len + 1);
/* check return value here ... */
memcpy(msg, some_string, len);
msg[len] = 0;
msglen = strlen (msg); /* this is to catch premature NULs */