c - 为什么我的 C 代码不能使用指针和结构体工作?

标签 c pointers malloc structure

为什么不起作用?存在地址访问错误。但是,我尝试通过互联网和谷歌找到问题所在,但找不到。我正在做我的作业。我的助手要求我们使用

STUDENT ** list  and Malloc ()

但是他们没有完美地解释,所以我很困难。我怎么解决这个问题?为什么我会收到错误?

最佳答案

看来您需要使用STUDENT **list,尽管这不是完成这项工作的最佳方式。但鉴于这是一个练习,我会坚持下去,并且 STUDENT **list 将是指向该 struct 的指针数组。

你的程序有两个主要错误。

  • 不为指针数组的每个元素分配内存
  • 将输入数据分配给本地结构,该结构被遗忘 函数退出。

当您尝试打印数据时,这两个中的第一个是致命的,因为您使用了未初始化的指针。

还有其他一些事情您应该经常检查

  • malloc返回的值
  • scanf 函数的结果(scanf返回的值)

此外,您必须

  • 限制字符串输入溢出
  • 使用后释放内存

这是代码的基本修复,仍然需要提到的其他改进。

#include <stdio.h>
#include <stdlib.h>

#define ID_LEN 7
#define NAME_LEN 10

typedef struct{
    char id[ID_LEN];
    char name[NAME_LEN];
    int math;
    int eng;
} STUDENT;

void SHOW(STUDENT* list) {
    printf("ID : %s\n", list->id);
    printf("name : %s\n", list->name);
    printf("math : %d\n", list->math);
    printf("eng : %d\n", list->eng);
}

void FirstList(STUDENT *list){
    printf("ID : ");
    scanf("%s", list->id);                  // use the pointer passed
    printf("Name : ");                      // instead of local struct
    scanf("%s", list->name);
    printf("Math score: ");
    scanf("%d",&list->math);
    printf("English score: ");
    scanf("%d",&list->eng);
}

int main(){
    STUDENT **list = NULL;
    int num = 0;
    printf("How many student? ");
    scanf("%d", &num);
    list = malloc(num * sizeof(STUDENT*));
    for(int i=0; i<num; i++) {
        list[i] = malloc(sizeof(STUDENT));  // allocate memory for struct
        FirstList(list[i]);
    }

    for(int i=0; i<num; i++) {
        SHOW(list[i]);
    }
    return 0;
}

关于c - 为什么我的 C 代码不能使用指针和结构体工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44352452/

相关文章:

c++ - 在复制构造函数中使用 memcpy 复制 QThread 指针

c - 重复调用后 realloc() 失败

c - 为什么 SIGINT 被发送到子进程并且什么都不做?

C++:使用 memcpy 时,myArray 和 &myArray 有什么区别?

c - 有没有办法获得有关整数提升的警告?

c++ - 无法将参数从 int * 转换为 const int *&

c - C 中的动态数组

c++ - malloc: *** 对象错误:未分配被释放的指针 *** 在 malloc_error_break 中设置断点以进行调试

c++ - 逗号运算符的局限性

C 从有符号 char 类型转换为 int 类型