gpt4 book ai didi

c - C中的sprintf,循环永远不会结束

转载 作者:太空狗 更新时间:2023-10-29 14:53:19 26 4
gpt4 key购买 nike

我遇到循环问题,我不知道为什么但循环永远不会结束。

int main(int argc, char *argv[])
{
int j;
char s[2];
for(j=1;j<=3;j++)
{
sprintf(s,"s%d",j);
printf("%s", s);
}
system("PAUSE");
return 0;
}

我认为循环应该在控制台中显示 s1s2s3。

最佳答案

char s[2]; 应该是 char s[3];,否则你会得到缓冲区溢出。


Abhineet解释为什么需要进行更改。但是,为了证实他的回答,这里是标准中的相关部分。

7.19.6.6

The sprintf function is equivalent to fprintf, except that the output is written into an array (specified by the argument s) rather than to a stream. A null character is written at the end of the characters written; it is not counted as part of the returned value. If copying takes place between objects that overlap, the behavior is undefined.

关于c - C中的sprintf,循环永远不会结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20517852/

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