你能否解决这段代码中的错误我得到的这个错误 error C2040: 'tmFunc' : 'char *()'在间接层次上有所不同'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(<ime);
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);
}
Run Code Online (Sandbox Code Playgroud)
因为您tmFunc在使用之前没有声明,所以它被隐式声明为返回的函数int.
在使用它之前声明它:
#include<stdio.h>
char *tmFunc(); // declaration
int main()
{
char *tmStamp=tmFunc();
}
Run Code Online (Sandbox Code Playgroud)
阳离子:你正在返回(tmbuf)局部变量的地址.
应该tmbuf[30];先复制 到动态内存并返回.
*tmFunc()之前也定义了功能main().
我更正了你的代码:
#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(<ime);
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;
}
Run Code Online (Sandbox Code Playgroud)
这实际上是正常的:
:~$ ./a.out
[2012/12/27 18:28:53]
Run Code Online (Sandbox Code Playgroud)
有范围问题.