yak yak - 1 year ago 103
C Question

Get current time in C, function

I want to get current time (without a current date) in C. The main problem is when I want to do it with functions. When I dont use them, evertyhing is just fine. Can anybody tell me, why my code shows only an hour? (take a look at the attached image). Thanks in advance.

#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;

enter image description here

Answer Source

The sizeof operator returns the length of the variable str_time which is a pointer to char. It doesn't returns the length of your dynamic array.

Replace sizeof(str_time) by 100 and it will go fine.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download