이것은 숙제 문제입니다. 내 컴파일러는 CodeBlocks입니다. 여기 for 루프에서 구조체를 사용하는 데 문제가 있습니다.
내 코드입니다 :#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'를 사용하여 line의 첫 번째'n' 문자를 구조 필드에 복사하십시오. –
또한 'malloc'의 반환을 캐스팅 할 필요가 없습니다. –