2011-10-18 23 views
2

私は教科書から構造の配列を説明するこの問題を微調整しようとしています。 私の出力は正しいですが、構造体に別の人物を追加し、結果をprintStats()の2番目のprint文で出力しようとすると、2行ではなく4行が出力されます。このコードを実行すると、次のとおりです。シンプルなC配列構造

 
Hoover, Adam: 10.400000 PPG in 2005 
, : 0.000000 PPG in 0 
.N=ö, Ðè/: 0.000000 PPG in 1 
Jane, Mary: 10.400000 PPG in 2005 

私は(メアリー・ジェーンの行を表示している)は、第2のprint文をコメントアウトしても、出力はまだ2行ですので、これは一種の面白いです - フーバー、アダムというライン1、 :0.00000が2行目です。配列[32]の4つのフィールドをすべて作成すると、4行の出力が得られますが、中間の2行は少し変更されます。

私はおそらく本当に単純なものがありませんが、目的はフーバー、アダム、ジェーン、メアリーと2行の出力を持つことだけです。

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


struct person { /* "person" is name for structure type */ 
    char first[32]; /* first field of structure is array of char */ 
    char last[32]; /* second field is array of char */ 
    int year; /* third field is int */ 
    double ppg; /* fourth field is double */ 

    char second[31]; 
    char third[31]; 
    int year1; 
    double ppo; 
}; /* ending ; means end of structure type definition */ 


displayStats(struct person Input) { 
     printf("%s, %s: %lf PPG in %d\n", Input.last, Input.first, Input.ppg, Input.year); 
     printf("%s, %s: %lf PPG in %d\n", Input.third, Input.second, Input.ppo, Input.year1); 
    } 

int main(int argc,char *argv[]) { 
    struct person teacher; 
    struct person another; 

    teacher.year=2005; 
    teacher.ppg=10.4; 
    strcpy(teacher.first,"Adam"); 
    strcpy(teacher.last,"Hoover"); 
    displayStats(teacher); 

    another.year1=2005; 
    another.ppo=10.4; 
    strcpy(another.second,"Mary"); 
    strcpy(another.third,"Jane"); 
    displayStats(another); 

    return (0); 
} 

答えて

1

先生のために、secondthirdが割り当てられていないので、あなたはゴミを見ていると、別のため、firstlastが割り当てられていませんか?

なぜsecondフィールドとthirdフィールドがありますか?それらを削除し、両方にfirstlastを使用し、displayStatsの2行目を削除すると正常に動作します。

+0

は、[最初と最後]に[第二と第三]変更はないでしょうフーバー、アダム・ラインを上書きしますか? – mdegges

+0

「teacher」と「another」はメモリの異なる部分にあるので、最初と最後のメンバーも異なっています。 – rmmh

+0

ありがとう、私はすべてのあなたの答えを組み合わせて動作するようになった。 – mdegges

1

displayStatsを呼び出すたびに2行が表示されます。これを2回呼び出すと4行が印刷されます。 displayStatsから2番目のprintfを削除すれば正常に動作します。

+0

問題は、各displayStat()呼び出しは1行だけを出力することです。 2番目のprintf文を削除すると、上から1行目と3行目が表示されます。 – mdegges

+0

「second」、「third」、「year1」、「ppo」の代わりに、「another」の値を 'first'、' last'、 'year'、' ppg'に設定する部分を変更します。 。 – Tim

+0

(main()の終わり近く、戻り呼び出しの直前) – Tim

1

構造体に不要なフィールドがあり、表示機能でprintfを2回呼び出しています。これらのフィールドを削除します。

struct person { /* "person" is name for structure type */ 
    char first[32]; /* first field of structure is array of char */ 
    char last[32]; /* second field is array of char */ 
    int year; /* third field is int */ 
    double ppg; /* fourth field is double */ 

    char second[31]; // <- Remove 
    char third[31]; // <- Remove 
    int year1; // <- Remove 
    double ppo; // <- Remove 
}; 

そしてへのあなたの表示機能を変更します。

void displayStats(struct person Input) { 
     printf("%s, %s: %lf PPG in %d\n", Input.last, Input.first, Input.ppg, Input.year); 
}