在屏幕上显示返回值的功能是错误的

问题描述:

我已经被这个非常简单的例子所打倒,最初似乎是这样,但最近它给了我很多头痛的问题。有人能告诉我这些功能有什么问题吗?在屏幕上显示返回值的功能是错误的

注意:我正在与C.一起工作,这是一项要求。

#include "stdafx.h" 
#include <string.h> 
#include <stdio.h> 

char* telegram_input() 
{ 
    char message[100]; 

    printf("Write down the telegram: "); 
    gets(message); 

    return message; 
} 


int _tmain(int argc, _TCHAR* argv[]) 
} 

     printf("Write your message:\n\n"); 
    char * myMessage; 

    myMessage = telegram_input(); 

     //HERE's the problem!!!!! --> 
     printf("The written message is: %s.", myMessage); 


    return 0; 
} 

的问题是,当我返回的数组中的值与字符*指针,这仅保持所述阵列的所述第一值和它是一个不正确的一个。 当我用'printf'打印它时,它会显示一个笑脸人物。那个怎么样? 这是为什么发生?如果我没有使用上述功能,我不会有这个问题。

+1

[你不能在C中返回数组](http://stackoverflow.com/questions/9995564/function-with-return-type-array-in-c)。另外,'gets'是错误的:使用'fgets'。 – netcoder 2013-02-28 19:51:29

+0

“返回值的函数” - 而不是函数的返回值? – 2013-02-28 20:01:40

您正在返回在堆栈上分配的变量的本地实例。如果你想正确做到这一点,有几种方法。你可以在堆上分配一个char数组,你必须在打印之后将其分配。另一种方法是返回static const char*然后打印。这种方法不是线程安全的,意味着如果任何其他线程会调用这个函数,数组中的数据当然会改变,给你一个意想不到的打印输出。甚至另一种方法是将想要写入消息的目的地传递给可能最有控制力的功能。我确信还有其他人,但这应该给你一些想法。

#include "stdafx.h" 
#include <string.h> 
#include <stdio.h> 

static const char* telegram_input_static() 
{ 
    static char message[100]; 

    printf("Write down the telegram: "); 
    gets(message); 

    return message; 
} 

char* telegram_input_heap() 
{ 
    char* message = malloc(sizeof(char) * 100); 

    printf("Write down the telegram: "); 
    gets(message); 

    return message; 
} 

void telegram_input_dest(char* dest) 
{ 
    printf("Write down the telegram: "); 
    gets(dest); 
}  

int _tmain(int argc, _TCHAR* argv[]) 
{ 

    printf("Write your message:\n\n"); 
    char * myMessage; 

    myMessage = telegram_input_heap(); 
    printf("The written message is: %s.", myMessage); 
    free(myMessage); 

    myMessage = (const char*)telegram_input_static(); 
    printf("The written message is: %s.", myMessage); 

    char destination[100]; 
    telegram_input_dest(destination); 
    printf("The written message is: %s.", destination); 

    return 0; 
} 
+0

好的,谢谢你的朋友!具有很大的意义。这两种方法似乎都是正确的。 还有一件事...如果我返回变量的指针而不声明它是静态的,将不会保持数据不变? – Leo 2013-02-28 19:57:13

+1

静态意味着持久性不是恒定的,这意味着它不在堆栈上,它专门在其他地方为它预留了空间。它更安全的将它作为const char *返回,以免人们不知所措并尝试释放它。你可以将它只是一个普通的char *,但是这会让人有点困惑,因为当内存真的“属于”该函数的使用时,你可能想改变它。 – ThePosey 2013-02-28 20:01:31

+0

您的第一个示例(使用静态)很有可能导致UB,如果该函数被调用一次,则存储返回值,然后再次调用,然后读取第一个调用的值:它将等同于修改常量通过一个非const限定值,即UB来限定值。 – netcoder 2013-02-28 20:15:14

消息是一个局部变量,你将返回它将被分配。你必须创建指针并发送它。然后在主要中删除它。

char* telegram_input() 
{ 
    char *message = malloc(sizeof(char) * (100)); 

    printf("Write down the telegram: "); 
    gets(message); 

    return message; 
} 

int _tmain(int argc, _TCHAR* argv[]) 
{ 

    printf("Write your message:\n\n"); 
    char * myMessage; 

    myMessage = telegram_input(); 

     //HERE's the problem!!!!! --> 
     printf("The written message is: %s.", myMessage); 

    free(myMessage); 
    return 0; 
}