-1

私はこの非常に単純な例に最初は戸惑いましたが、最近は頭を悩ませています。誰かがこれらの機能の何が問題なのか教えてもらえますか?

注: 私は 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;
}

問題は、配列の値を char* ポインターに返すと、配列の最初の値のみが保持され、それが正しくないことです。「printf」で印刷すると、笑顔の文字が表示されます。それはどうですか?なぜこれが起こるのですか?上記の機能を使用していなければ、この問題は発生しませんでした。

4

2 に答える 2

2

スタックに割り当てられている変数のローカル インスタンスを返しています。正しく実行したい場合は、いくつかのアプローチがあります。ヒープに char 配列を割り当てることができ、印刷後に割り当てを解除する必要があります。もう 1 つの方法は、 a を返してから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;
}
于 2013-02-28T19:51:11.987 に答える
0

メッセージはローカル変数であり、割り当てられるそれを返しています。ポインタを作成して送信する必要があります。次に、メインで削除します。

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;
}
于 2013-02-28T19:54:27.707 に答える