2017-06-04 51 views
0

爲什麼doens不工作?存在地址訪問錯誤。但是,我試圖通過互聯網和谷歌找到問題,我不知道。我正在做我的任務。我的助理要求我們使用爲什麼我的c代碼不能使用指針和結構?

STUDENT ** list and Malloc() 

然而,他們沒有完全解釋,所以我在困難時期。我怎麼解決這個問題?爲什麼我得到一個錯誤?

回答

0

看來你是需要使用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; 
} 
+0

謝謝你的回答,我還有一個問題。那麼我應該把免費()的代碼?....你能再幫我一次嗎?:) – Codingdumb

+0

在程序結束。你應該「釋放」數組元素指向的循環,然後是數組本身的「空閒」 - 與對malloc執行的操作相反。 –