繁体   English   中英

在函数中更改struct tm的值

[英]changing values of struct tm in function

我正在开发一个函数,该函数应提示用户输入任意时间和日期。 这些值我想存储在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未初始化时,这是正确的。 指针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;
}

在您牢牢掌握了指针之前,使用简单结构可能会更容易(这不仅包括在堆上分配内存)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM