Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 views
in Technique[技术] by (71.8m points)

c - localtime() function shows two equals date

Why when i try to show 2 dates with different arguments, that i put into localtime() function, console show 2 equal dates?

This is my code:

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

int main() {
    time_t time1, time2;
    struct tm *timeinfo1, *timeinfo2;
    char *time1str, *time2str;

    time1 = 3600;
    time2 = 3720;
    timeinfo1 = localtime(&time1);
    timeinfo2 = localtime(&time2);

    time1str = asctime(timeinfo1);
    time2str = asctime(timeinfo2);
    puts(time1str);
    puts(time2str);

    getch();
    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Data wouldn't persist between two calls to localtime or asctime. You have to copy data somewhere. Here is corrected example (still have little issue with strncpy):

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

int main() {
    time_t time1, time2;
    struct tm timeinfo1, timeinfo2, *ti;
    char time1str[256], time2str[256], *tstr;

    time1 = 3600;
    time2 = 3720;
    ti = localtime(&time1);
    memcpy(&timeinfo1, ti, sizeof(*ti));
    ti = localtime(&time2);
    memcpy(&timeinfo2, ti, sizeof(*ti));

    tstr = asctime(&timeinfo1);
    strncpy(time1str, tstr, sizeof(time1str) - 1);
    tstr = asctime(&timeinfo2);
    strncpy(time2str, tstr, sizeof(time1str) - 1);

    puts(time1str);
    puts(time2str);

    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...