【发布时间】:2021-10-17 21:27:01
【问题描述】:
我正在尝试构建一个程序,该程序具有一个学生 id 数组、一个指向字符串文字的 char 指针的课程代码数组以及一个注册表二维数组,用于保存学生是否注册课程或不是。到目前为止,我正在添加工作正常的学生。当我总共输入 1 门课程时,该程序也按预期运行。然而,问题是当我尝试向 courseArray 添加超过 1 个课程代码时,输入代码后出现分段错误。我不确定如何解决这个问题,而且这件事上的任何资源似乎都没有为我指明正确的方向。对此的任何帮助表示赞赏。
#include <stdio.h>
#include "Functions.h"
#include <stdbool.h>
int main()
{
//declaring variables for number of students and courses
int numStudents, numCourses;
//declaring 2d array for the registration table
int registrationTable[numStudents][numCourses];
//prompting user input for number of students and storing in numStudents
printf("How many students would you like to register: \n");
scanf("%d", &numStudents);
//create student array based on numStudents
int studentArray[numStudents];
//Prompting user input for id's of students in student array
for (int i = 0; i < numStudents; i++)
{
printf("Please enter the student ID for student %d: \n", i + 1);
scanf("%d", &studentArray[i]);
}
//Prompting user input for number of courses offered and storing in numCourses
printf("How many courses are you offering: \n");
scanf("%d", &numCourses);
//create couses array based on numCouses
char *courseArray[numCourses];
//Prompting user input for course codes in course array
for (int i = 0; i < numCourses; i++)
{
printf("Please enter the course code for course %d: \n", i + 1);
scanf(" %s", courseArray[i]);
}
validate(studentArray, courseArray, numStudents, numCourses);
return 0;
}
【问题讨论】:
-
你在给它们一个值之前使用
numStudents和numCourses(int registrationTable[numStudents][numCourses];) -
但是您要问的问题是您在为其分配值之前使用
courseArray[i](scanf(" %s", courseArray[i]);)。scanf %s需要一个指向内存的指针,它可以在其中存储字符串,但您尝试读取未初始化的内存。char courseArray[numCourses][MAX_COURSE_NAME_LEN + 1]; -
char *courseArray[numCourses]分配一个指向 char 的指针数组,而不是一个 c 字符串数组。您需要初始化该指针数组以指向分配的存储空间。也许考虑改用char的二维数组 -
@ikegami 我还没有在我的程序中使用registrationTable,所以感谢您指出这一点。我想我可能理解这个问题,另一个用户提到使用 malloc 在内存中创建空间,在这种情况下这是必要的吗?如果是这样,我只是困惑为什么当我只在课程数组中创建 1 个指针时一切正常。
-
Re "我还没有在我的程序中使用registrationTable,所以感谢您指出这一点。",即便如此,像你一样使用它是未定义的行为,因此足以使程序崩溃。