如何访问指向结构的指针中的成员?

问题描述:

在我的头,我有:如何访问指向结构的指针中的成员?

#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

变化

*(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:为什么你不想在访问数组时使用数组符号?指针很棒,但数组也是如此。使用数组符号,因为它更紧凑,如果没有别的;它也一般更清晰。 –

您应该使用

AccountList[Counter].Name 

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

你*应该*使用第一个,但你*可以*使用第二个。 :-) –

你有两个选择,以摆脱这种错误的。访问结构成员名或密码或者使用

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

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

更换或者在你的整个代码上面提到的两个。

+0

箭头符号很有趣,在其他答案中没有提及。发现得好! –

+0

谢谢乔纳森! –