2012-12-27 21 views
2

能否請你修正這個錯誤在此代碼中,我得到這個錯誤error C2040: 'tmFunc' : 'char *()'區別間接水平從'int()'C錯誤C2040?字符*()「中的間接水平不同於‘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); 
} 
+1

請同時使用一個真正的主函數'int main(void)',並請正確縮進代碼。 –

+0

你也可以考慮在你的'tmFunc()'函數中返回一個本地字符緩衝區的地址,除非是靜態的,(它不是)是未定義的行爲。 – WhozCraig

回答

5

陽離子:要返回局部變量的地址(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(&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; 
} 

,實際上是正常工作:

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

有範圍的問題。

+0

感謝您的回覆。它在分配內存後工作。 – Vicky

7

因爲你沒」在使用前聲明tmFunc,它隱式聲明爲返回int的函數。

就宣佈它在使用它之前:

#include<stdio.h> 

char *tmFunc(); // declaration 

int main() 
{ 
char *tmStamp=tmFunc(); 
} 
+0

感謝您的回覆。這很有幫助。 – Vicky