2

我正在尝试更多地了解C,我想知道是否有人可以澄清这里发生了什么。我收到编译器警告:“警告:赋值从指针生成整数而无需强制转换 @ 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";

谢谢,感谢您的帮助!

4

3 回答 3

2

您正在尝试将指向字符串文字的指针分配给char. 将双引号更改"为单引号',如下所示:

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

请注意,我更改msglen+1len - 1最后分配的字符的索引。

于 2013-01-21T21:36:58.387 回答
1

"\0" 被视为常量字符串,并且当您尝试执行此操作时,该字符串的地址会被放置到位,msg[len - 1] = "\0"因此您会收到消息“converts...”

改为这样做msg[len - 1] = '\0'

于 2013-01-21T21:45:22.363 回答
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 */
于 2013-01-21T21:41:44.227 回答