zogboy809
January 6th, 2016, 04:47 PM
The function below works but the compiler issues a warning and I would like to understand why. Is there a better way to do this?
The function should just return a formatted string that I want to print to stdout and also write to a file in my main program.
format.h: In function ‘printDate’:
format.h:30:2: warning: return from incompatible pointer type [enabled by default]
return &buffer;
^
format.h:30:2: warning: function returns address of local variable [-Wreturn-local-addr]
char* printDate() {
time_t tm;
struct tm *ltime;
time( &tm );
ltime = localtime( &tm );
ltime->tm_mon++;
ltime->tm_year += 1900;
char buffer [50];
sprintf( buffer, "%02i:%02i:%02i ---- %02i-%02i-%04i",
ltime->tm_hour, ltime->tm_min, ltime->tm_sec,
ltime->tm_mday, ltime->tm_mon, ltime->tm_year );
return &buffer;
}
The function should just return a formatted string that I want to print to stdout and also write to a file in my main program.
format.h: In function ‘printDate’:
format.h:30:2: warning: return from incompatible pointer type [enabled by default]
return &buffer;
^
format.h:30:2: warning: function returns address of local variable [-Wreturn-local-addr]
char* printDate() {
time_t tm;
struct tm *ltime;
time( &tm );
ltime = localtime( &tm );
ltime->tm_mon++;
ltime->tm_year += 1900;
char buffer [50];
sprintf( buffer, "%02i:%02i:%02i ---- %02i-%02i-%04i",
ltime->tm_hour, ltime->tm_min, ltime->tm_sec,
ltime->tm_mday, ltime->tm_mon, ltime->tm_year );
return &buffer;
}