数组索引中的变量不更改其值

时间:2019-12-08 22:43:47

标签: c

我有一个名为student的结构数组和一个变量num

当我尝试访问学生数组的索引num时,它不起作用。
当我尝试打印其内容时,它会显示hf

我的代码:

typedef struct {
  char subject[50];
  int grade;
} SUBJECTS;

void viewSubjects(SUBJECTS student[], int size, int *numberOfSubjects) {
  for (int i = 0; i < *numberOfSubjects; i++) {
    printf("\n%s-\t%d\n", student[i].subject, student[i].grade);
  }
}

void addSubject(SUBJECTS student[], int size, int *numberOfSubjects) {
  char newSubject[50];
  int exists = 0, grade = 0, num = (*numberOfSubjects) + 1;
  do {
    exists = 0;
    printf("What's the name of the subject?\n");
    scanf("%s", newSubject);
    for (int i = 0; i < *numberOfSubjects; i++) {
      if (strcmp(student[i].subject, newSubject) == 0) {
        exists = 1;
        break;
      }
    }
  } while (exists == 1);
  strcpy(student[num].subject, newSubject);
  do {
    printf("What was the grade for %s?\n", newSubject);
    scanf("%d", &grade);
  } while (grade < 0 || grade > 20);
  student[num].grade = grade;
  ++(*numberOfSubjects);
}

int main(void) {
  int numberOfSubjects = 1, menuAction = 1;
  SUBJECTS student[50];
  strcpy(student[0].subject, "arroz");
  student[0].grade = 19;
  do {
    menuAction = menu();
    if (menuAction == 1) {
      addSubject(student, sizeof(student) / sizeof(student[0]),
          &numberOfSubjects);
    } else if (menuAction == 2) {
      viewSubjects(student, sizeof(student) / sizeof(student[0]),
          &numberOfSubjects);
    }
  } while (menuAction != 0);
  return 0;
}

2 个答案:

答案 0 :(得分:0)

没关系,我已经弄清楚了。我将numberOfSubjects初始化为1,然后加1,所以当调用第二个位置时,结果是不可预测的,因为我更改了第三个位置(索引2)的值。

答案 1 :(得分:0)

addSubjects()在偏移量num = (*numberOfSubjects) + 1处附加新条目。相反,它应使用偏移量num = *numberOfSubjects处的条目,并测试此索引是否低于size,以避免写入超出数组末尾的地方。