2017-01-27 7 views
-1

構造体の変数(ファーストネーム*)に名前を入力する必要があります mallocで なぜプログラムを実行するのが失敗するのか分かりません。そのあるべき (例えば、デヴィッドのための)名前を挿入イム とは、名前を取得し、ポインタFIRST_NAME * のサイズを変更し、ネストされた構造体 - 入力

誰かが私を理解するのに役立ちます* FIRST_NAMEするために、文字列の一時をコピーし、その後一時配列 に入れてなぜそれが機能しないのですか?

"ReadPerson"機能を探します。

typedef struct{ 
    int day, month, year; 
} Date; 

typedef struct{ 
    char *first_name, *last_name; 
    int id; 
    Date birthday; 
} Person; 

void ReadDate(Date *a) 
{ 
    printf("insert day, month, year\n"); 
    scanf("%d%d%d", &a->day, &a->month,&a->year); 
} 

void ReadPerson(Person *b) 
{ 
    char temp_first_name[21]; 
    char temp_last_name[21]; 

    printf("insert first name:\n"); 
    gets(temp_first_name); 
    b->first_name = (char*)malloc(strlen(temp_first_name)+1); 
    strcpy(b->first_name,temp_first_name); 
    //need to check malloc (later) 

    printf("insert last name:\n"); 
    gets(temp_last_name); 
    b->last_name = (char*)malloc(strlen(temp_last_name)+1); 
    strcpy(b->last_name, temp_last_name); 
    //need to check malloc (later) 

    printf("insert id\n"); 
    scanf("%d",&b->id); 

    printf("insert person's birthday:\n"); 
    ReadDate(b); 
} 

ありがとうございます。私はプログラムする理由を理解していない

+1

コンパイルしますか? 'ReadDate(b);' 'Person *'型の 'b'を' Date * 'を期待する関数に渡します。 –

+0

'malloc()'の戻り値をキャストすべきではない理由を調べるには、[here](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc)をチェックしてください。 – naccyde

答えて

1

は、それはあなたが互換性のない型を代用しようとしているとまともなコンパイラがそのことについてあなたに言っているはずだからだ、

まあの実行に失敗しています。

{ 
    ... 
    ReadDate(b);   // error here 
} 

あなたはbタイプPerson *である見ることができるように、あなたはDate *タイプを期待する関数void ReadDate(Date *a)に渡し:

のは、機能void ReadPerson(Person *b)の終わりを見てみましょう。

これはおそらく単純なタイプミスです。ちょうどこれをReadDate(&b->birthday);に変更してください。

+0

助けてくれてありがとう.. –

関連する問題