c - 尝试在 C 中分配和调用嵌套结构的值时出现“段错误”错误

标签 c pointers struct nested segmentation-fault

好吧,我对 C 相当陌生,只知道基本的 C 函数,我正在尝试创建一个程序,让用户创建一个学生 - 一个结构 - 并更新他/她的个人和学术详细信息 - 也结构体和学生结构体的成员。

//student.h
struct personalDetails {
            char name[20];
            char phoneNum[13];
            char address[30];
    };

struct classRecords {
        int assignment;
        int midterm;
        int finalMark;
        int total;
};

struct student{
        struct personalDetails det;
        struct classRecords rec;
}st1, *st1_ptr,
 st2, *st2_ptr,
 st3, *st3_ptr,
 st4, *st4_ptr,
 st5, *st5_ptr;

每当我运行程序并到达用户必须输入要分配给结构或从结构调用的值的部分时,我都会收到段错误。以下是我分配值的示例之一的代码:

//operations.c
#include<stdio.h>
#include"student.h"
#include<string.h>

extern struct personalDetails det; // name, phoneNum, address
extern struct classRecords rec; // assignment, midterm, finalMark, total
extern struct student st1; // student 1
extern struct student *st1_ptr; // student 1 pointer
extern struct student st2;
extern struct student *st2_ptr;
extern struct student st3;
extern struct student *st3_ptr;
extern struct student st4;
extern struct student *st4_ptr;
extern struct student st5;
extern struct student *st5_ptr;
struct student *studentID(int id) { // identifies student by ID

if (id == 1) {
        return st1_ptr;
}
else if (id == 2) {
        return st2_ptr;
}
else if (id == 3) {
        return st3_ptr;
}
else if (id == 4) {
        return st4_ptr;
}
else if (id == 5) {
        return st5_ptr;
}
}
char name[20];
void updateName() { // updates student name
printf("Enter student's name\n");
scanf("%19s", name);

strcpy(studentID(1)->det.name, name);

}
void main() {
updateName();
printf("Student1 Name: %s", studentID(1)->det.name);
}

欢迎任何建议,但请记住我对 C 的了解非常少。请记住,我不知道如何正确使用指针(可能在代码中很明显),但如果有人可以解释如何在这种情况下使用它们,那就太好了。另外,从我在其他帖子中看到的内容来看,使用 malloc 和 sizeof 似乎是此类问题的常见答案,但如果可能的话,我想远离它们,因为我的教授没有提到需要其中任何一个这些功能。提前致谢

编辑1:添加初始化到帖子

最佳答案

For starters, where are the st1_ptr, str2_ptr, etc values assigned? – kaylum

I do not have them assigned to anything at the moment(that I know of)! I think I need to assign them accordingly to st1, st2, etc but I do not know how to do that properly. – rsorce

你根本不需要那些指针;只需删除它们的所有声明,并将所有剩余的 st1_ptr 替换为 &st1 等即可。

关于c - 尝试在 C 中分配和调用嵌套结构的值时出现“段错误”错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34123693/

相关文章:

c - 从函数返回时小数部分丢失

c - 如何快速重绘图像缓冲区

c - RAM 内存中的段

arrays - 序列化异构数组

c - 读取行中的字并将字存储在 3D 数组中

pointers - 无法反射(reflect)不返回指针,编译器在转换时出现 panic ?

c - 关于 c 指针和 * & 运算符的问题

c++ - 为什么建议在删除后将指针设置为null?

c - 我在链表的末尾创建一个垃圾节点只是为了指定 NULL。我怎样才能修改我的代码来防止这种情况发生?

c++ - 如何为结构体数组分配内存?