为什么我的c代码不能使用指针和结构?

时间:2017-06-04 09:09:37

标签: c pointers malloc structure

为什么它会起作用?存在地址访问错误。但是,我试图在整个互联网和谷歌上找到问题,我还没准备好。我在做我的任务。我的助手要求我们使用

alert()

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

1 个答案:

答案 0 :(得分:0)

似乎您必需使用STUDENT **list,尽管这不是完成工作的最佳方式。但是看到这是一个练习,我将继续使用它,STUDENT **list将是指向struct的一系列指针。

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

  • 不为指针数组的每个元素分配内存
  • 将输入数据分配给遗忘的本地struct 功能退出。

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

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

  • malloc
  • 返回的值
  • scanf函数的结果(值{em>返回 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;
}