2016-11-27 6 views
0

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

私は、私は次のようなエラー」のエラーを取得するコンパイル構造体または共用体 "と呼びます。どのように私は実際にメンバーを含む構造体で私の割り当てられた領域を埋めるのですか?

+2

また、(*(AccountList + Counter))を書くこともできますが、AccountList [Counter] .Nameを可読性のために使用します... – Byte

答えて

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); 
    } 
+0

配列記法を使用しないでこれを行う方法はありますか? –

+0

@DustinH:なぜ配列にアクセスする際に配列表記法を使用したくないのですか?ポインタは素晴らしいですが、配列もそうです。配列記法を使用するのは、それがもっとコンパクトだからです。それは一般的にもより明確です。 –

1

あなたはどちらか

AccountList[Counter].Name 

または

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

最初のものを使うべきですが、2番目のものを使うことはできます*。 :-) –

3

あなたはこのエラーを取り除くために2つの選択肢があります使用する必要があります。アクセス構造体のメンバは、名​​前またはパスワードのいずれか

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

または

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

を使用しては、あなたの全体のコードで上記の2つのどちらかを交換してください。

+0

矢印の表記は面白く、他の回答では言及されていません。よく目撃された! –

+0

ありがとうジョナサン! –

関連する問題