0
我正在处理一个应该提示用户输入任意时间和日期的函数。 这些值我要在结构TM存储,但它不能正常工作:函数中更改struct tm的值
struct tm * enter_time_GMT(){
struct tm *TIME;
char input[50];
int check=0, buffer;
printf("date:\n");
do{
printf("day > ");
scanf("%49s",&input[0]);
buffer=atoi(input);
if(buffer>=1 && buffer<=31){
check=1;
/* program crashes here, compiler says TIME uninitialized: */
TIME->tm_mday=buffer;
}
else{
check=0;
printf("wrong input\n");
}
}while(check==0);
/* just a short part of the full function */
return TIME;
}
我使用的功能是这样的:
int main(){
struct tm *sysTIME; /* why does the compiler want me to use tm* instead of tm? */
char buffer[80];
sysTIME=enter_time_GMT();
strftime(buffer, 80, "%d.%m.%Y %H:%M:%S", sysTIME);
printf("%s\n", buffer);
return 0;
}
令我惊讶我可能会使用类似的东西
TIME->tm_year=12;
在main()中工作,但不在我的函数中。那么区别在哪里,struct tm和其他结构有什么区别?
您正在返回一个指向局部变量TIME的指针,该变量一旦离开该函数就会超出范围。 – 2014-08-29 09:14:55
有没有人有提示如何避免这种情况?我现在卡住了。迄今我所测试的替代品都失败了。 – van 2014-08-29 09:32:28
'struct tm * TIME;' - >'struct tm * TIME = malloc(sizeof struct tm);'。在你的程序中你不会初始化TIME指针,因此崩溃。 – 2014-08-29 09:34:23