gpt4 book ai didi

c - 无法将字符串写入 *char[]

转载 作者:行者123 更新时间:2023-11-30 20:10:33 24 4
gpt4 key购买 nike

我已经为此花费了几个小时,但几乎没有取得任何进展。我需要知道为什么我的程序在调用 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我已经尝试过这个,它似乎工作正常,但我仍然遇到输出不正确的问题。我应该能够迭代数组并打印每个下标中的字符串。

最佳答案

问题来自malloc(total_courses + sizeof(course_collection))

您只分配 course_collection 的指针数组。您需要为整个struct Course分配内存

应该是ma​​lloc(total_courses * sizeof(struct Course))

关于c - 无法将字符串写入 *char[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44877694/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com