Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Help with basics: Call on a function (http://www.go4expert.com/forums/help-basics-function-t23587/)

duckdace 16Oct2010 17:36

Help with basics: Call on a function
 
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
      }
  }
}


jimblumberg 16Oct2010 19:05

Re: Help with basics: Call on a function
 
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 17Oct2010 20:34

Re: Help with basics: Call on a function
 
...and so well described as well. Thanks!


All times are GMT +5.5. The time now is 06:40.