gpt4 book ai didi

c - 如何解释 sprintf 的这种行为?

转载 作者:太空宇宙 更新时间:2023-11-04 01:02:59 24 4
gpt4 key购买 nike

所以情况很简单:我需要在 c 字符串前面添加一个字符。

所以我有我的代码:

char *a = "2233b";
char output[100];
char toAdd = '-';

strcpy(output, a);
printf("\noutput=%s", output);
sprintf(output, "%c%s", toAdd, a);
printf("\noutput=%s", output);

并且输出符合预期:

output=2233b
output=-2233b

好的,到目前为止一切顺利。现在情况变了,我想在 c 字符串之前添加更多字符,所以我这样配置代码:

char *a = "2233b";
char output[100];
char toAdd = '-';

strcpy(output, a);
printf("\noutput=%s", output);
sprintf(output, "%c%s", toAdd, a);
printf("\noutput=%s", output);
sprintf(output, "%c%s", toAdd, output);
printf("\noutput=%s", output);

我期望输出是:

output=2233b
output=-2233b
output=--2233b

但事实并非如此,我的屏幕上打印了以下输出:

output=2233b
output=-2233b
output=-------

Check working example here

为什么输出包含这个值?
因为格式只是字符 (%c) toAdd ('-') 和字符串 (%s) 是 output 并包含 ("-2233b")。

那么为什么最后的输出不包含 "--2233b"?而output的字符怎么都变成了'-'呢?

最佳答案

我认为问题出在

 sprintf(output, "%c%s",  toAdd, output);

在这里,您在单个顺序语句中读取和写入output。这会调用 undefined behaviour .

引用 C11,章节 §7.21.6.6,sprintf() 函数

If copying takes place between objects that overlap, the behavior is undefined.

关于c - 如何解释 sprintf 的这种行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31247505/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com