簡體   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