gpt4 book ai didi

c - sprintf 的返回值影响数组

转载 作者:行者123 更新时间:2023-11-30 17:47:36 24 4
gpt4 key购买 nike

#include<stdio.h>

int main(){

unsigned char array[]={0xff,0xd8,0xff,0xe0};
char names[7];
int count=1;
sprintf(names,"%03d.jpg",count);
for(int i=0;i<4;i++){
printf("%#x ",array[i]);
}
printf("\n");
return 0;
}

字符数组受sprintf的返回值影响,这里是7。我用gdb发现了这个错误。
如何摆脱这个问题以及
如何知道 sprintf 行执行后发生了什么。 ###

output should be : 0xff 0xd8 0xff 0xe0
but Output I got is : 0 0xd8 0xff 0xe0

最佳答案

sprintf(names, "%03d.jpg", count);

将字符串“001.jpg”存储在names中,您可以通过在sprintf之后打印它来找到它。由于 NUL 字符,该字符串需要 8 个字节来存储,而不是 7 个字节,因此您有未定义的行为。在这种特定情况下,NUL 被写入 array[0],它恰好与内存中的 names 相邻。

关于c - sprintf 的返回值影响数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18888569/

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