這是一個家庭作業問題。我的編譯器是CodeBlocks。使用for循環中的struct問題
這裏是我的代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Address{
char number[5];
char street[30];
char city[30];
};
struct Employee{
char ID[7];
char name[31];
struct Address *addr;
};
int main(){
int n,i;
char temp[7];
printf("Enter number of Employee : ");
scanf("%d",&n);
struct Employee **p=(struct Employee **)malloc(n*sizeof(struct Employee *));
for (i=0; i<n; i++)
{
p[i]=(struct Employee *)malloc(sizeof(struct Employee));
p[i]->addr=(struct Address *)malloc(sizeof(struct Address));
}
for(i=0; i<n; i++)
{
printf("Employee #%d\n",i+1);
printf("Enter ID : ");
gets(p[i]->ID);
printf("Enter Name : ");
gets(p[i]->name);
printf("Enter Home number : ");
gets(p[i]->addr->number);
printf("Enter Street : ");
gets(p[i]->addr->street);
printf("Enter City : ");
gets(p[i]->addr->city);
}
}
我的問題是,當我運行這段代碼,我不能爲#1名員工輸入ID;但是,我可以輸入員工#2和#3的ID。
我的問題在哪裏?
因爲'scanf'在後面留下換行符。也不要使用'gets',你的代碼是可怕的(沒有冒犯,但所有那些(非常小!)固定大小的緩衝區,沒有檢查...) – user786653
我秒這。考慮閱讀['getline'](http://www.crasseux.com/books/ctutorial/getline.html#getline),並使用'strncpy'將行的第一個'n'字符複製到結構字段中。 –
也沒有必要施放'malloc'的返回。 –