我的目标是替换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或得到警告?
memcpy(buffer, replacement, strlen(replacement));
是您要寻找的。
另一种(非常模糊的)方式:
char c = buffer[strlen(replacement)];
buffer[snprintf(buffer, sizeof buffer, "%s", replacement)] = c;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句