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;
}
解决方案
没关系,我已经想通了。我初始化numberOfSubjects
为 1,然后加 1,所以在调用第二个位置时,结果是不可预测的,因为我更改了第三个位置(索引 2)的值。
推荐阅读
- aws-cdk - AWS CDK 如何处理假设返回列表而不是字符串的 Fn.getAtt
- java - 没有主键和可为空字段的休眠实体
- python - 复杂类型列的熊猫不兼容形状
- google-bigquery - 在 ON 中使用 CASE 语句进行 LEFT JOIN 时出现 BigQuery 错误
- angular - 使用 AngularFirestore 时如何处理大数据?
- python - 虽然我可以看到 pip3 安装顺利,但无法安装 python 插件
- android - 如何在设备而不是主机上进行简单的单元测试
- get - 如何使用标记动画获取 lat 和 lgn 的值
- python - 有两个轮廓 cv2.findContour 只找到一个
- python - 循环以移动 DataFrame Datetime 中列的时间线