2016-10-16 59 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"; 
}