当我运行这个程序时,struct崩溃了

时间:2014-09-29 16:23:24

标签: c segmentation-fault typedef

我正在练习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;
}

1 个答案:

答案 0 :(得分:3)

您创建一个包含2个元素的数组:

    struct employee record[2];
                           ^----

实际上是record[0]record[1]。但是你试着分配一个未定义的THIRD元素:

    record[2].empId=3;
           ^---

这意味着你要在未分配/未定义的内存空间中进行涂鸦。