C Error C2040? char *()' differs in levels of indirection from 'int ()'

13,560

Solution 1

Cation: you are returning address (tmbuf) of local variable.

  • Should copy tmbuf[30]; first into dynamic memory and return that.

  • Also defined *tmFunc() function before main().

I corrected your code:

#include<stdio.h>
#include<time.h>
#include<string.h>
#include<stdlib.h>

char *tmFunc() {
  char tmbuf[30];
  char *buff; 
  struct tm *tm;
  time_t ltime;             /* calendar time */
  ltime=time(NULL);         /* get current cal time */
  tm = localtime(&ltime);
  sprintf (tmbuf, "[%04d/%02d/%02d %02d:%02d:%02d]", tm->tm_year + 1900,
       tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);

       buff = calloc(strlen(tmbuf)+1,sizeof(char));
       strcpy(buff, tmbuf);
       return buff;

  return (buff);
}


int main()
{
   char *tmStamp=tmFunc();
   printf("Time & Date : %s \n", tmStamp);
   free(tmStamp);
   return 1;
}

That is actually working correctly:

:~$ ./a.out 
[2012/12/27 18:28:53]  

there was Scope problems.

Solution 2

Because you didn't declare tmFunc before usage, it's implicitly declared as a function returning int.

Just declare it before you use it:

#include<stdio.h>

char *tmFunc();  // declaration

int main()
{
char *tmStamp=tmFunc();
}
Share:
13,560
Vicky
Author by

Vicky

Updated on June 17, 2022

Comments

  • Vicky
    Vicky almost 2 years

    Could you please fix the error in this code I get this error error C2040: 'tmFunc' : 'char *()' differs in levels of indirection from 'int ()'

    #include<stdio.h>
    main()
    {
        char *tmStamp=tmFunc();
    }
    
    char *tmFunc() 
    {
        char tmbuf[30];
        struct tm *tm;
        time_t ltime;             /* calendar time */
        ltime=time(NULL);         /* get current cal time */
        tm = localtime(&ltime);
        sprintf (tmbuf, "[%04d/%02d/%02d %02d:%02d:%02d]", tm->tm_year + 1900,
           tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
        return(tmbuf);
    }
    
  • Vicky
    Vicky over 11 years
    Thanks for the response. It worked after allocating the memory.
  • Vicky
    Vicky over 11 years
    Thanks for the response. It was helpful.