gpt4 book ai didi

c - sprintf 的奇怪工作

转载 作者:太空宇宙 更新时间:2023-11-04 05:13:48 25 4
gpt4 key购买 nike

#include<stdio.h>
#include<time.h>
int main(){
char filepath[100];
char datevar[15];
char command[30];
struct tm *t1;
time_t now ;
time(&now);
memcpy(&t1,localtime(&now),sizeof(t1));
t1 = localtime(&now);
memset(filepath,0,sizeof(filepath));
sprintf(datevar,"%04d%02d%02d",t1->tm_year+1900,t1->tm_mon+1,t1->tm_mday);
strcpy(filepath,"abc");
strcat(filepath,"/xyx/");
strcat(filepath,datevar);
strcat(filepath,"/");
printf("filepath 1:- %s\n",filepath);
sprintf(command, "hello %s good path",filepath);
printf("filepath 2:- %s\n",filepath);
return 0;
}

在上面的程序中,printf 都打印了不同的filepath。我得到的输出:-

filepath  1:- abc/xyx/20130430/
filepath 2:- h

我的问题是,如果我在 sprintf 中使用它,为什么文件路径会更改。

最佳答案

因为

char command[30];

空间不够大

sprintf(command, "hello %s good path",filepath);

看起来好像最后的 'h' 和 0 终止符进入了 文件路径。 (这纯属巧合,因为 sprintf进入 command` 超出了它所能容纳的范围会调用未定义的行为。)

关于c - sprintf 的奇怪工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16292478/

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