Help with basics: Call on a function

duckdace's Avatar, Join Date: Oct 2010
Light Poster
I'm making a program where the logname and time appear onscreen before each input. Problems arise however, when I try to make myself an own getTime-function. It's propably the simplest thing to do, but I'm not able to call on the function, and receive a proper return-value. I believe the following code-bit is close to doing as it is supposed, but it won't compile. Some of the messages are:

warning: return makes integer from pointer without a cast
warning: function returns address of local variable

Code:
char getTime() {
  char t[10];
  struct timeval tv;
  time_t timeNow;
  gettimeofday(&tv, NULL);
  timeNow=tv.tv_sec;
  strftime(t,10,"%T",localtime(&timeNow));
  return t;
}
int main() {
   char input[200];
   while(1) {
      char ctime[10] = getTime();    //This is where my fundamentals are wrong
      printf("%s %s ", getenv("LOGNAME"),ctime);
      if (fgets(input, sizeof(input), stdin) != NULL) {
        //do something
      }
   }
}
0
jimblumberg's Avatar
Ambitious contributor
Code:
char getTime() {
  char t[10];

  return t;
}
1. Your function is defined as returning a char and you are trying to return a char *.
2. t[10] is local to getTime(). When getTime returns t will go out of scope, deleting t[10].

There are a couple of ways to solve this problem.

One way is to change
Code:
char getTime()
to
Code:
char* getTime()
and changing
Code:
 char t[10];
to
Code:
 static char t[10];
Another way is to pass arguments to getTime().
Code:
void getTime(char *t)
{
  struct timeval tv;
  time_t timeNow;
  gettimeofday(&tv, NULL);
  timeNow=tv.tv_sec;
  strftime(t,10,"%T",localtime(&timeNow));
}
and in main change
Code:
   char ctime[10];
   while(1) {
      getTime(ctime);    //This is where my fundamentals are wrong
Jim
duckdace like this
0
duckdace's Avatar, Join Date: Oct 2010
Light Poster
...and so well described as well. Thanks!