繁体   English   中英

为什么我的C代码无法使用指针和结构?

[英]Why doesn't my c code work using pointer and struct?

为什么不起作用? 存在地址访问错误。 但是,我试着在整个互联网和Google上查找问题,但我没有。 我正在做作业。 我的助手要求我们使用

STUDENT ** list  and Malloc ()

但是他们并不能很好地解释,所以我很难受。 我怎么解决这个问题? 为什么会出现错误?

似乎您需要使用“ STUDENT **list尽管这不是完成这项工作的最佳方法。 但是看到这是一个练习,我将继续学习,并且STUDENT **list将是指向该struct的指针数组。

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

  • 不为指针数组的每个元素分配内存
  • 将输入数据分配给在函数退出时忘记的本地struct

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

还有其他事情你应该经常检查

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

另外,你必须

  • 防止字符串输入溢出
  • 使用后free内存

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

#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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM