다음 코드가 있습니다. 구조체 정의에서, 나는 사용자에게 직원의 성과 이름을 입력하도록 요청합니다. 그러나이 exe를 실행하면 제목이 입력 된 후에 종료됩니다. 어떤 제안?gets()에 전달할 때 struct에서 포인터를 사용하는 것이 잘못된 이유는 무엇입니까?
#include<stdio.h>
#include<string.h>
#define NUMEMPS 10
struct Employee {
char *firstname;
char *lastname;
char *title;
int salary;
};
int main()
{
struct Employee* stuff = malloc(NUMEMPS* sizeof *stuff);
int n,i;
for (n=0; n<NUMEMPS;n++)
{
printf("Please enter number %d Employee's Last name:", n);
fflush(stdout);
gets(stuff[n].lastname);
if (strlen(stuff[n].lastname) == 0)
break;
printf("Please enter number %d Employee's first name:", n);
fflush(stdout);
gets(stuff[n].firstname);
printf("Please enter number %d Employee's title:", n);
fflush(stdout);
gets(stuff[n].title);
printf("Please enter number %d Employee's salary:", n);
fflush(stdout);
scanf("%d", &stuff[n].salary);
getchar();
}
for (i = 0;i<n;i++)
{
printf("{%s,%s,%s,%d}\n",
stuff[i].lastname,
stuff[i].firstname,
stuff[i].title,
stuff[i].salary);
}
return 0;
}
'gets()'를 사용하지 마십시오. 더 이상 표준 C의 일부가 아니며 다른 문제와 관계없이 사용하기에 절대 안전하지 않습니다. 'fgets()'또는'getline()'대신에 결과 문자열에 구분 기호 (개행)를 포함하고있는 반면에'gets()'는 그것을 제외한다는 것을 기억하십시오. 그리고 모든 입력 작업의 결과를 확인하십시오. –
@JonathanLeffler : [http://pubs.opengroup.org/onlinepubs/9699919799/functions/getline.html] ('getline')은 POSIX에 의해 정의되지만 C 표준에 의해 정의되지는 않습니다. 모든 시스템에 존재하지 않거나 동일한 이름의 다른 기능이있을 수 있습니다. –
@KeithThompson : 예; 그 이유는'fgets()'를 먼저 쓰는 이유인데, 평소와 같이 URL을 포함시키지 않았거나 명시 적으로'getline()'을 POSIX 전용으로 호출하지 않았다는 것을 인정합니다. 이 줄에 관한 –