2017-07-14 59 views
1

返回動態數組變量的隨機值我有以下問題..: 我運行我的代碼,它可以正確讀取任意數量的作者,但是當我繼續將作者的全名和日期打印到我得到(例如)屏幕這樣的:從結構體

Example console log

正如你所看到的名稱字符串/ char值是正確的,但對於日期的整數值只是隨機數..

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

typedef struct{ 
    char lastName[30]; 
    char firstName[30]; 
    Date birthday; 
}Person; 

int main(){ 

    //assigning memory dynamically to array of authors 
    int n; 
    printf("How many authors should be added to the archive?\n"); 
    scanf("%i", &n); 

    //array of authors 
    Person* authors = (Person*) calloc(n, sizeof(Person)); 

    //reading authors 
    int i; 
    for(i = 0; i < n; i++){ 
     addAuthor(authors, i); 
    } 

    //writing authors to screen 
    for(i = 0; i < n; i++){ 
     printAuthor(authors[i]); 
    } 

    free(authors); 
    return 0; 
} 

Date inputDate(){ 
    Date d; 
    printf("Input year: "); 
    scanf(" %s", &d.year); 
    printf("Input month: "); 
    scanf(" %s", &d.month); 
    printf("Input day: "); 
    scanf(" %s", &d.day); 
    return d; 
} 

Person inputAuthor(){ 
    Person p; 
    printf("\nInput last name: "); 
    scanf(" %s", &p.lastName); 
    printf("Input last name: "); 
    scanf(" %s", &p.firstName); 
    p.birthday = inputDate(); 
    return p; 
} 

void printAuthor(Person p){ 
    printf("\n%s, %s born %i.%i.%i", p.lastName, p.firstName, p.birthday.day, p.birthday.month, p.birthday.year); 
} 

void addAuthor(Person* p, unsigned u){ 
    p[u] = inputAuthor(); 
} 
+1

'%s'用於讀取字符串,而不是整數。 –

+0

2nd'printf(「Input last name:」);' - >'printf(「Input first name:」);' – BLUEPIXY

回答

1

你'重新讀取的時間不正確:

printf("Input year: "); 
scanf(" %s", &d.year); 
printf("Input month: "); 
scanf(" %s", &d.month); 
printf("Input day: "); 
scanf(" %s", &d.day); 

這些字段是int類型的,但%s格式說明期望一個指向一個char陣列。使用不正確的格式說明符調用undefined behavior

要讀取整數值,請使用%d格式說明符。

printf("Input year: "); 
scanf("%d", &d.year); 
printf("Input month: "); 
scanf("%d", &d.month); 
printf("Input day: "); 
scanf("%d", &d.day); 
+0

謝謝!哈哈這樣一個小錯誤讓我尋找幾個小時... –