-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