2

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!

2
  • 2
    You're using strncpy(). That's almost certainly not the best solution. Commented Jan 21, 2013 at 21:39
  • msglen = strlen(msg); has potential for undefined behaviour, since strncpy doesn't usually 0-terminate. Commented Jan 21, 2013 at 21:43

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It seems to be initialized to 10 and never changed afterwards. But that would present a problem before that line.
1

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'

1 Comment

+1 the answer please, if you think this helped :-) @txcotrader
0
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 */

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.