【发布时间】:2021-02-08 18:54:30
【问题描述】:
我的目标是替换字符串中的前n (3) 个字符,而不会收到任何编译器警告或触发未定义的行为:
const char *replacment = "abc";
char buffer[128] = "xxx-remainder";
我正在使用 gcc (GCC) 9.2.0 和标准库:
-
使用
sprintf似乎是在replacement中插入 NUL 字符,即使我认为我告诉它不要这样做:sprintf(buffer, "%.3s", replacement); printf("%s\n", buffer); /// prints "abc", not "abc-remainder" -
使用
strncpy会引发警告:strncpy(buffer, replacement, 3);这会触发以下警告:
test.c: In function 'main': main.c:8:5: warning: 'strncpy' output truncated before terminating nul copying 3 bytes from a string of the same length [-Wstringop-truncation] 8 | strncpy(buffer, replacement, 3); | ^~~~~~~~~~~~~~~~~~~~~~~~~~~在这种情况下,输出看起来很好。
-
当然,我可以使用
for循环手动复制字符,但我会尽量避免这种情况。
如何修复此处显示的任何一种方法,或者什么替代函数调用可以让我替换前 3 个字符而不在字符串中插入 NUL 或收到警告?
【问题讨论】: