1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

Help with basics: Call on a function

Discussion in 'C' started by duckdace, Oct 16, 2010.

  1. duckdace

    duckdace New Member

    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
          }
       }
    }
    
    
    
     
  2. jimblumberg

    jimblumberg New Member

    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 likes this.
  3. duckdace

    duckdace New Member

    ...and so well described as well. Thanks!
     

Share This Page