我已经在这里工作了几个小时,取得的进展甚微。我需要知道为什么我的程序在调用scanf()时崩溃。错误消息:“分段错误;核心转储”导致我相信我没有正确地为动态数组分配内存。如果是这种情况,有人可以告诉我如何正确地分配内存来添加一个结构到数组?无法将字符串写入* char []
#include <stdio.h>
#include <stdlib.h>
/*
*
*/
enum Subject{
SER = 0, EGR = 1, CSE = 2, EEE = 3
};
struct Course{
enum Subject sub;
int number;
char instructor_name[1024];
int credit_hours;
}*course_collection;
int total_courses = 0;
int total_credits = 0;
void course_insert();
void resizeArray();
int main(int argc, char** argv) {
int choice = 0;
while(choice != 4){
printf("Welcome to ASU, please choose from the menu"
"choices.\n\n");
printf("_____________________________________________\n\n");
printf("Menu:\n 1.Add a class\n 2. Remove a class\n"
" 3.Show classes\n 4.Quit");
printf("\n\nTotal credit hours: %d\n\n", total_credits);
printf("\n\n_________________________________________");
scanf("%d", &choice);
if(choice == 1){
resize_array(total_courses);
course_insert();
}
else if(choice == 3)
print_courses();
}
return (EXIT_SUCCESS);
}
void resize_array(int total_courses) {
course_collection = malloc(total_courses +
sizeof(course_collection));
}
void print_courses() {
int i;
for(int i = 0; i < total_courses; i++){
printf("\nInstructor: %s\n\n",
course_collection[i].instructor_name);
}
}
void course_insert(){
printf("\n\nEnter the instructor's name\n\n");
scanf("%s" , course_collection[total_courses].instructor_name);
total_courses++;
}
//will crash just after scanf();
//must press 1 & enter for correct output
输入几个教练的名字后,我从菜单中选择第三个选项,并应通过数组迭代并打印出每个教练的名字,但我得到的是空白行,最后教官的名字,我估算。
UPDATE @ user3545894我试过这个,它似乎工作正常,但我仍然得到的问题与输出不正确。我应该可以遍历数组并在每个下标中打印字符串。
普莱斯e将其降低到能够再现问题的[mcve]。或者单步执行您自己的调试器中的代码。 –
我不明白为什么这个代码应该工作。你永远不会创建一个数组。 –
启用编译器警告。 – EOF