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