Dustin H Dustin H - 5 days ago 5
C Question

How do I access Members in a Pointer to Structs?

In my header I have:

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


and in my main function I have:

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


When I compile I get the following error "error: request for member 'Name' in something not a structure or union". How do I actually fill my allocated space with structs that contain the members?

Answer

change

*(AccountList+Counter)

to

AccountList[Counter]

or

(*(AccountList+ Counter)).

This is my solution

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);
    }
Comments