首页 > 解决方案 > 数组索引中的变量不改变其值

问题描述

我有一个称为结构的数组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;
}

标签: c

解决方案


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


推荐阅读