【发布时间】:2017-07-03 04:12:06
【问题描述】:
我已经做了几个小时了,但进展甚微。我需要知道为什么我的程序在调用 scanf() 时会崩溃。错误消息:“分段错误;核心转储”让我相信我没有正确地将内存分配给动态数组。如果是这种情况,有人可以告诉我如何正确分配内存以将一个结构添加到数组中吗?
#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
输入几个讲师姓名后,我从菜单中选择第三个选项,它应该遍历数组并打印每个讲师的姓名,但我得到的只是空白行和我估算的最后一个讲师姓名。
更新 @user3545894 我已经尝试过了,它似乎工作正常,但我仍然遇到输出不正确的问题。我应该能够遍历数组并打印每个下标中的字符串。
【问题讨论】:
-
请将其减少为重现问题的minimal reproducible example。或者在您自己的调试器中单步调试代码。
-
我不明白为什么这段代码应该工作。你永远不会真正创建一个数组。
-
启用编译器警告。
-
course_collection是一个指针,所以你可能想要sizeof *course_collection。我没有看到total_courses在任何地方定义,但您的意思是:course_collection = malloc(sizeof *course_collection * total_courses);?
标签: c arrays struct dynamic-memory-allocation