2016-10-16 57 views
-2

我試圖用C來寫一個函數,獲取整型作爲參數並返回一個字符數組(或字符串)字符串int值。函數返回,而不是用C

const char * month(int x) 
{ 
    char result[40]; 
    if(x<=31) strcpy(result,"can be a day of the month"); 
    else strcpy(result,"cannot be a day of the month"); 
    return result; 
} 

但我的函數返回一個int,而不是一個字符串。我已閱讀,人們可能會碰到類似情況的帖子,但我不明白的指針式功能是如何工作的,以及如何使他們返回我想要的(我已經證明一點關於指針和我有關於怎樣的想法他們獨立工作,但我從來沒有嘗試過寫一段代碼,增加了一些功能對他們來說,就像做一個解決方案更有效或別的東西。)

+1

'result'。返回的指針是無效的,並且取消引用它是未定義的行爲。 –

+0

當函數退出時'結果'超出範圍和生命。有很多這樣的問題。 –

+0

這是C代碼還是C++代碼?兩種語言的答案完全不同。 –

回答

1

考慮到這是一個C代碼。 (不知道C++) 這裏你最好的選擇是具有的功能範圍之外聲明result,然後傳遞您使用的是您可以與您的數據填寫(一定要不會溢出)在函數內部的指針。在您使用的內容中,result將被銷燬,您將無法使用它。

void month(int x, char* result) 
{ 
    if(x<=31) strcpy(result,"can be a day of the month"); 
    else strcpy(result,"cannot be a day of the month") 
} 

這只是一個建議,你可以返回一些錯誤代碼或任何你想要的。

+0

爲了存儲所述結果的值,是否需要一個char []類型或字符串當我打電話在INT主函數()?我知道這是一個愚蠢的問題,但我以前沒有使用過指針。 – Stevie

+0

假設你使用C而不是C++,C中沒有字符串支持,所以你需要聲明char []。 – Kiloreux

+0

它工作得很好。謝謝 :) – Stevie

4
const char * month(int x) 
{ 
    char result[40]; 
    if(x<=31) strcpy(result,"can be a day of the month"); 
    else strcpy(result,"cannot be a day of the month"); 
    return result; 
} 

這沒有意義。您返回一個指向數組的指針,但函數返回後,數組不再存在,因爲result是該函數的局部。

對於C:

const char * month(int x) 
{ 
    if(x<=31) return "can be a day of the month"; 
    return "cannot be a day of the month"; 
} 

對於C++:與自動範圍的對象被銷燬在函數返回時

std::string month(int x) 
{ 
    if(x<=31) return "can be a day of the month"; 
    return "cannot be a day of the month"; 
}