2014-08-29 77 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; 
} 

使用普通的结构是可能更容易,直到你有一个指针牢牢把握(其中包括超过在堆上分配内存)。