簡體   English   中英

為什么time.h中定義的“時間”函數返回NULL?

[英]Why would the function 'time' as defined in time.h return NULL?

我有使用'time'函數和'time.h'中其他函數的代碼,並且'time'每次'time'返回NULL(哈哈雖然不好笑,但是我可以集中精力處理'time'的代價很高重新執行此類注意。 奇怪的是,這只是從昨天開始。 以前在相同但沒有(我一直在添加)代碼的情況下使用相同功能證明是可以的。 以下是C89代碼:

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

#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1

typedef struct tm tm;

int logf(char input_string[])
{
    time_t* current_time_since_epoch;
    time(current_time_since_epoch);
    if (current_time_since_epoch == NULL)
    {
        printf("'time' returned NULL.\n");
        return EXIT_FAILURE;
    }
    tm* current_time_calandar_time = localtime(current_time_since_epoch);
    if (current_time_calandar_time == NULL)
    {
        printf("'localtime' returned NULL.\n");
        return EXIT_FAILURE;
    }
    char current_time_textual_representation[20];
    strftime(current_time_textual_representation, 20, "%d-%m-%Y %H:%M:%S", current_time_calandar_time);
    printf("%s\n", current_time_textual_representation);
    printf("%s\n", input_string);
    return EXIT_SUCCESS;
}

int main(void)
{
    int check_logf = logf("Hello.");
    if (check_logf == 0) exit(EXIT_SUCCESS);
    else
    {
        printf("'logf' returned EXIT_FAILURE.\n");
        exit(EXIT_FAILURE);
    }
}

當您將time_t的地址傳遞給time()它將結果存儲在該地址。 由於您沒有分配任何內存來存儲結果(您所做的只是聲明了一個未初始化的指針),因此您將獲得未定義的行為。 只需將NULL傳遞給time ,它將返回該值。

time_t current_time_since_epoch = time(NULL);

如果要提供結果作為參數,則需要為time()函數分配內存以存儲結果。 在堆棧上聲明變量或調用malloc() 如果給你也可以檢索返回值NULL作為參數。

time_t current_time_since_epoch;
time(&current_time_since_epoch);
// or
current_time_since_epoch = time(NULL);
// or
time_t* timePtr = (time_t*) malloc(sizeof(time_t));
time(timePtr);
// ...
free(timePtr);

有關函數time()原型的更多信息,請參見此處

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM