我已經在這裏工作了幾個小時,取得的進展甚微。我需要知道爲什麼我的程序在調用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