结构数组在最后一个索引处失败

时间:2015-03-12 22:47:44

标签: c

#include <stdio.h>
#include <string.h>
#include <string.h>
struct student
{
     int id;
     char name[30];
     float percentage;
};

int main()
{
     int i;
     struct student record[2];

     // 1st student's record
     record[0].id=1;
     strcpy(record[0].name, "Raju");
     record[0].percentage = 86.5;

     // 2nd student's record
     record[1].id=2;
     strcpy(record[1].name, "Surendren");
     record[1].percentage = 90.5;

     // 3rd student's record
     record[2].id=3;

     //strcpy(record[2].name, "Thiyagu");//--->Bug in this line

     //record[2].percentage = 81.5;//--->Bug in this line


     for(i=0; i<3; i++)
     {
         printf("     Records of STUDENT : %d \n", i+1);
         printf(" Id is: %d \n", record[i].id);
         printf(" Name is: %s \n", record[i].name);
         printf(" Percentage is: %f\n\n",record[i].percentage);
     }
     return 0;
}

我很难调试这段代码。由于某种原因,我标记的行( - &gt;)会破坏代码。现在这行以及下面的行被注释掉了,因为代码没有用它们执行。我有一种感觉,它必须使用null终止符做一些事情。

1 个答案:

答案 0 :(得分:6)

struct student record[2];表示该数组包含2个条目。有效索引为01

尝试访问record[2]会导致undefined behaviour