[英]How do I access Members in a Pointer to Structs?
在標題中,我有:
#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);
當我編譯時,出現以下錯誤“錯誤:請求成員“名稱”的不是結構體或聯合體”。 我實際上如何用包含成員的結構填充分配的空間?
您有兩種選擇可以擺脫此錯誤。 使用以下方式訪問結構成員的名稱或密碼:
(AccountList+Counter)->Name
(AccountList+Counter)->Password
要么
AccountList[Counter].Name
AccountList[Counter].Password
在整個代碼中替換上面提到的兩個。
更改
*(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);
}
您應該使用
AccountList[Counter].Name
要么
(*(AccountList + Counter)).Name
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.