[英]Why does this C code treat a local struct as a pointer, when it doesn't appear to be a pointer?
[英]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.