gcc 4.4.4 c89
如何标准地使字符串以空字符结尾?当我使用NULL
时,会收到警告信息。
*dest++ = 0;
*dest++ = '\0';
*dest++ = NULL; /* Warning: Assignment takes integer from pointer without a cast */
源代码:
size_t s_strscpy(char *dest, const char *src, const size_t len)
{
/* Copy the contents from src to dest */
size_t i = 0;
for(i = 0; i < len; i++)
*dest++ = *src++;
/* Null terminate dest */
*dest++ = 0;
return i;
}
另一个问题:我故意注释掉了在结尾处加上空字符的那一行。然而,它仍然正确地打印出了 dest 的内容。该函数的调用者将通过包含空字符或不包含空字符来发送字符串的长度,即 strlen(src) + 1 或 strlen(src)。
size_t s_strscpy(char *dest, const char *src, const size_t len)
{
/* Copy the contents from src to dest */
size_t i = 0;
/* Don't copy the null terminator */
for(i = 0; i < len - 1; i++)
*dest++ = *src++;
/* Don't add the Null terminator */
/* *dest++ = 0; */
return i;
}
*dest++ = '\0';
,因为在这个上下文中,'\0'
的类型是正确的。 - Paul R