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

时间:2016-11-27 17:47:39

标签: c

在我的标题中,我有:

#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);

当我编译时,我得到以下错误“错误:请求成员'名称'在非结构或联合的东西中”。如何使用包含成员的结构实际填充分配的空间?

3 个答案:

答案 0 :(得分:3)

您有两种选择可以消除此错误。使用

访问结构成员名称或密码
(AccountList+Counter)->Name 
(AccountList+Counter)->Password

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

在整个代码中替换上面提到的两个中的任何一个。

答案 1 :(得分: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);
    }

答案 2 :(得分:1)

你应该使用

AccountList[Counter].Name

(*(AccountList + Counter)).Name