-2
我只是在练习C,我试图创建一个带有多个元素的结构并循环并打印出结构中的所有数据。但是,当我运行这个程序时,我得到了分段错误。我有点困惑,为什么会发生这种情况,因为我可以在没有任何警告或失败的情况下编译它,并且程序运行它也会在最后崩溃。当我运行这个程序时结构崩溃
这里是输出,当我运行程序:
lnx-v1:242> ./multiArrayStruct
Records of EMPLOYEE : 1
Id is: 1
First name is: Joe
Last name is: Johnson
Employee age is 25
Records of EMPLOYEE : 2
Id is: 2
First name is: Kyle
Last name is: Korver
Employee age is 25
Records of EMPLOYEE : 3
Id is: 3
First name is: Adam
Last name is: Thompson
Employee age is 25
Segmentation fault (core dumped) <-------why is this crashing ?
这里是我的代码,以及:
#include <stdio.h>
#include <string.h>
struct employee
{
int empId;
char empNameFirstName[20];
char empNameLastName[20];
int empAge;
};
int main()
{
struct employee record[2];
// First employee record
record[0].empId=1;
strcpy(record[0].empNameFirstName, "Joe");
strcpy(record[0].empNameLastName, "Johnson");
record[0].empAge=25;
// second employee record
record[1].empId=2;
strcpy(record[1].empNameFirstName, "Kyle");
strcpy(record[1].empNameLastName, "Korver");
record[1].empAge=25;
// third employee record
record[2].empId=3;
strcpy(record[2].empNameFirstName, "Adam");
strcpy(record[2].empNameLastName, "Thompson");
record[2].empAge=25;
for(int i = 0; i < 3;i++)
{
printf(" Records of EMPLOYEE : %d \n", i+1);
printf(" Id is: %d \n", record[i].empId);
printf(" First name is: %s \n", record[i].empNameFirstName);
printf(" Last name is: %s \n", record[i].empNameLastName);
printf(" Employee age is %d\n", record[i].empAge);
}
return 0;
}
你应该确保你标记了你正在使用的语言。如果影响了渲染的代码,并且让那些知道C的人更容易找到。 – crashmstr 2014-09-29 16:25:58
使用'[2]'的数组有两个条目,[[0 ]'和'[1]'。 '[2]'无法访问。 – crashmstr 2014-09-29 16:27:03