获取当前时间C,功能

yak*_*yak 1 c time

我想在C中获取当前时间(没有当前日期).主要问题是当我想用函数做的时候.当我不使用它们时,evertyhing就好了.任何人都可以告诉我,为什么我的代码只显示一个小时?(看一下附图).提前致谢.

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

char* get_time_string()
{
    struct tm *tm;
    time_t t;
    char *str_time = (char *) malloc(100*sizeof(char));
    t = time(NULL);
    tm = localtime(&t);
    strftime(str_time, sizeof(str_time), "%H:%M:%S", tm);
    return str_time;
}

int main(int argc, char **argv)
{
    char *t = get_time_string();
    printf("%s\n", t);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

sim*_*onc 7

sizeof(str_time)给你的大小char*.您想要缓冲str_time点的大小.尝试

strftime(str_time, 100, "%H:%M:%S", tm);
//                 ^ size of buffer allocated for str_time
Run Code Online (Sandbox Code Playgroud)

其他小问题 - 你应该包括在打印其内容后<stdlib.h>选择定义malloc和应该.free(t)main