2011-10-18 54 views
2

我一直試圖從我的教科書中解釋這個問題,解釋結構數組。 我的輸出是正確的,但是當我在結構中添加另一個'person',並嘗試打印結果(在displayStats()的第二個打印語句中)時,它輸出4行而不是2行。運行此代碼時,輸​​出是:簡單的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線 - 胡佛,亞當是1號線,和:0.00000是第2行。當我在數組[32]中創建所有4個字段時,我仍然得到4行輸出,但中間的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未分配?

爲什麼你有secondthird字段?刪除它們,使用firstlast兩個,並刪除第二行displayStats,它應該工作。

+0

會不會改變[第二和第三]至[第一個和最後]覆蓋胡佛,亞當線? – mdegges

+0

編號'老師'和'另一個'在記憶的不同部分,所以他們的第一個和最後一個成員也是不同的。 – rmmh

+0

謝謝,我把它的所有答案都結合起來了。 – mdegges

1

每次調用displayStats打印兩行。調用兩次打印四行。從displayStats中刪除第二個printf,它應該可以工作。

+0

事情是,每個displayStat()調用應該只打印一行。當我刪除第二個printf語句時,我從上面得到第一行和第三行。 – mdegges

+0

改變你將'another's values設置爲'first','last','year'和'ppg'的部分,而不是'second','third','year1'和'ppo' 。 – Tim

+0

(接近main()的末尾,就在返回調用之前) – Tim

1

你的結構中有不必要的字段,你在顯示函數中調用printf兩次。刪除這些字段:

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); 
}