我正在努力解決結構指標及其在函式中的用法。在這里,我有一個問題。下面的代碼沒有列印我希望它列印的 ID、名稱和分數。我花了幾個小時試圖弄清楚這一點。誰能用通俗易懂的方式解釋一下?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct examinee
{
char ID[8];
char name[32];
int score;
};
struct examinee* init(char ID[8], char name[32], int score){
struct examinee* instance;
instance = (struct examinee*)malloc(sizeof(struct examinee));
strcpy(instance->ID, ID);
strcpy(instance->name, name);
instance->score;
return instance;
};
int main(int argc, char *argv[])
{
struct examinee examinee_1;
struct examinee* examinee_1_ptr = init("IO760","Abe",75);
examinee_1_ptr= &examinee_1;
printf("examinee's information:\nID: %s\nname: %s\nscore: %d\n", examinee_1_ptr->ID, examinee_1_ptr->name, examinee_1_ptr->score);
return 0;
}
uj5u.com熱心網友回復:
在這一行
struct examinee* examinee_1_ptr = init("IO760","Abe",75);
您執行該函式并將結果存盤在examinee_1_ptr變數中。
但是這兩行
struct examinee examinee_1;
examinee_1_ptr= &examinee_1;
創建一個空examinee實體并用該空白實體的地址覆寫指標。此時,您創建的那個init()已經丟失,因為沒有任何東西指向它的地址,所以您無法訪問它。洗掉這兩行,你會沒事的。
printf("examinee's information:\nID: %s\nname: %s\nscore: %d\n", examinee_1_ptr->ID, examinee_1_ptr->name, examinee_1_ptr->score);
請注意,這里您僅通過指標訪問物件。首先不需要有examinee_1變數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/480169.html
