2016-11-27 129 views
0

在我的頭,我有:如何訪問指向結構的指針中的成員?

#define MAXSTRSIZE 20 
struct Account{ 
    char* Name; 
    char* Password; 
}; 

,並在我的主要功能我:

struct Account* const AccountList=malloc(sizeof(struct Account)*AccountAmount)//AccountAmount is just an int value input by the user 
FILE* File = fopen(FileName,"r"); 
int Counter;//Counter for the For Loop 
for (Counter=0;Counter<AccountAmount;Counter++) 
{ 
    *(AccountList+Counter).Name=malloc(sizeof(char)*MAXSTRSIZE); 
    *(AccountList+Counter).Password=malloc(sizeof(char)*MAXSTRSIZE); 
    fscanf(File,"%s%s",*(AccountList+Counter).Name,*(AccountList+Counter).Password); 

我編譯時出現以下錯誤「錯誤:請求成員‘名稱’的東西不結構或聯合「。我如何真正用包含成員的結構填充我分配的空間?

+2

你也可以寫(*(AccountList + Counter))。Name ...但爲了可讀性使用AccountList [Counter] .Name ... – Byte

回答

2

變化

*(AccountList+Counter) 

AccountList[Counter] 

(*(AccountList+ Counter)). 

這是我的解決方案

struct Account* const AccountList=malloc(sizeof(struct Account)*AccountAmount);//AccountAmount is just an int value input by the user 
    FILE* File = fopen(FileName,"r"); 
    int Counter;//Counter for the For Loop 
    for (Counter=0;Counter<AccountAmount;Counter++) 
    { 
     AccountList[Counter].Name = malloc(sizeof(char)*MAXSTRSIZE); 
     AccountList[Counter].Password = malloc(sizeof(char)*MAXSTRSIZE); 
     fscanf(File,"%19s%19s", AccountList[Counter].Name,AccountList[Counter].Password); 
    } 
+0

有沒有辦法做到這一點,而不使用數組符號? –

+0

@DustinH:爲什麼你不想在訪問數組時使用數組符號?指針很棒,但數組也是如此。使用數組符號,因爲它更緊湊,如果沒有別的;它也一般更清晰。 –

1

您應該使用

AccountList[Counter].Name 

(*(AccountList + Counter)).Name 
+1

你*應該*使用第一個,但你*可以*使用第二個。 :-) –

3

你有兩個選擇,以擺脫這種錯誤的。訪問結構成員名或密碼或者使用

(AccountList+Counter)->Name 
(AccountList+Counter)->Password 

AccountList[Counter].Name 
AccountList[Counter].Password 

更換或者在你的整個代碼上面提到的兩個。

+0

箭頭符號很有趣,在其他答案中沒有提及。發現得好! –

+0

謝謝喬納森! –

相關問題