我一直試圖從我的教科書中解釋這個問題,解釋結構數組。 我的輸出是正確的,但是當我在結構中添加另一個'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);
}
會不會改變[第二和第三]至[第一個和最後]覆蓋胡佛,亞當線? – mdegges
編號'老師'和'另一個'在記憶的不同部分,所以他們的第一個和最後一個成員也是不同的。 – rmmh
謝謝,我把它的所有答案都結合起來了。 – mdegges