首页 文章

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

提问于
浏览
0

在我的 Headers 中我有:

#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 回答

  • 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);
        }
    
  • 3

    你有两个选择来摆脱这个错误 . 使用访问结构成员名称或密码

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

    要么

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

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

  • 1

    你应该使用

    AccountList[Counter].Name
    

    要么

    (*(AccountList + Counter)).Name
    

相关问题