0
#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.

4

2 回答 2

6

这是因为

char command[30];

不够大,无法容纳

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

看起来 final'h'和 0 终止符进入filepath. (Which is coincidental, sincesprintfing more into命令,而不是它可以容纳调用未定义的行为。)

于 2013-04-30T05:06:49.250 回答
3

与这个问题无关,但你有一个更严重的问题,那就是:

memcpy(&t1,localtime(&now),sizeof(t1));

在这里,您使用&t1,它获取指针的地址,这意味着您将指针传递给memset指向 a 的指针struct tm,换句话说struct tm **。您还使用sizeof(t1)which 是指针的大小,而不是它可能指向的大小,并且取决于平台,它将是四个或八个字节。

既然你之后直接做

t1 = localtime(&now);

memset实际上不需要调用。

于 2013-04-30T05:10:20.413 回答