这是一个家庭作业问题。我的编译器是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'的返回。 –