简体   繁体   中英

How to use pointers with struct members

Last week in my computer science class, we wrote a program that contained a function that imported "cards" from a file like so:

  struct card
  {
  char rank[10];
  char suit[10];
  char color;
  bool dealt;
  char location[12];
  };

.

  void importCard(card deck[])
  {
  ifstream fin;
  fin.open("deck.txt");
  int index;  

  for(index=0;index<52;index++)
  {

  fin >> deck[index].rank;
  fin >> deck[index].suit;

  if(deck[index].suit[0]==('d')||deck[index].suit[0]==('h'))
     {
     deck[index].color='r';
     }
  else
     {
     deck[index].color='b';
     }

  deck[index].dealt=false;
  }
  }

Basically, I HEAVILY use the dot operator within this function.

NOW, my assignment is to revise this to use pointers in place of all square brackets. However, it doesn't work if I use something like

fin >> *deckPointer.suit;

because pointer don't work with dot operators. So, how do I write this to loop through all the cards? I know how I would write it to loop through one card, but I don't know how I would make it loop through all the cards. Also, I can't use any other, more advanced tools, like vectors, so don't suggest that. Also, I am ONLY allowed to increment my pointers with ++ and --, not by any other amount.

Pointers work with dot operators, it's their precedence that is wrong. You can throw in some parentheses to fix it:

 fin >> (*deckPointer).suit;

There is a convenient shorthand for this in c++ syntax: -> operator, combining pointer dereference and field access:

find >> deckPointer->suit;

Here's a hint for you:

card* temp = &deck[index];

is the same as

card *temp = deck;
temp += index;

then you can use -> to get at pointed to values. As this is homework, I don't want to go much further.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM