2014-08-29 79 views
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和其他結構有什麼區別?

+0

您正在返回一個指向局部變量TIME的指針,該變量一旦離開該函數就會超出範圍。 – 2014-08-29 09:14:55

+0

有沒有人有提示如何避免這種情況?我現在卡住了。迄今我所測試的替代品都失敗了。 – van 2014-08-29 09:32:28

+0

'struct tm * TIME;' - >'struct tm * TIME = malloc(sizeof struct tm);'。在你的程序中你不會初始化TIME指針,因此崩潰。 – 2014-08-29 09:34:23

回答

0

當您的編譯器說TIME未初始化時,它是正確的。你的指針TIME沒有指向任何有意義的地方,訪問它可能會導致程序崩潰。

從你的評論我看到你還不熟悉指針。在這種情況下,您可以直接使用struct tm。這樣你就不必擔心內存管理,因爲struct是按值傳遞的。

如果你想使用指針,你必須使指針指向有效的內存。一種方法是用malloccalloc在堆上分配內存。那麼這個記憶就可以從你的功能以外的地方訪問,但是如果你不再需要它,你應該在以後使用free

下面的示例程序使用這兩種方法:xmas工作指針和newyear作品與普通struct tm

#include <stdlib.h> 
#include <stdio.h> 
#include <time.h> 

struct tm *xmas(int year) 
{ 
    struct tm *t = calloc(1, sizeof(*t)); // must be free'd after use 

    t->tm_mday = 24; 
    t->tm_mon = 11; 
    t->tm_year = year - 1900; 

    return t; // pointers to memory on the heap can be safely returned 
} 

struct tm newyear(int year) 
{ 
    struct tm t = {0}; 

    t.tm_mday = 1; 
    t.tm_mon = 0; 
    t.tm_year = year - 1900; 

    return t; // structure is returned "by value" 
}  

int main() 
{ 
    struct tm *x = xmas(2014); 
    struct tm ny = newyear(2015); 
    char buf[30]; 

    strftime(buf, sizeof(buf), "%D", x); 
    puts(buf); 

    strftime(buf, sizeof(buf), "%D", &ny); 
    puts(buf); 

    // Free ressources of allocated memory 
    free(x); 

    return 0; 
} 

使用普通的結構是可能更容易,直到你有一個指針牢牢把握(其中包括超過在堆上分配內存)。