Thread: Accessing structure members

  1. #1
    Registered User mc088's Avatar
    Join Date
    Jan 2017
    Posts
    19

    Accessing structure members

    Hi,

    The code below is an example from my C book, which displays "Ace of Spades" using three different ways given the struct.

    Just wondering. which way is the best and why?


    Thank you.


    Code:
    #include <stdio.h>
    
    struct card
    {
        char *face;
        char *suit;
    };
    
    
    int main()
    {
        struct card aCard;       
        struct card *cardPtr;    
    
    
        aCard.face = "Ace";
        aCard.suit = "Spades";
    
    
        cardPtr = &aCard;    /*    assign address of aCard to cardPtr    */
        
        printf( "%s%s%s\n%s%s%s\n%s%s%s\n", aCard.face, " of ", aCard.suit,
         cardPtr->face, " of ", cardPtr->suit, 
         ( *cardPtr ).face, " of ", ( *cardPtr ).suit ); 
    
    
        printf("\n");
        return 0;
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by mc088
    The code below is an example from my C book, which displays "Ace of Spades" using three different ways given the struct.

    Just wondering. which way is the best and why?
    Generally, you should prefer cardPtr->face to ( *cardPtr ).face because the syntactic sugar makes it easier to read, so you should not use the third way here.

    However, since you don't need the pointer in the first place, the first way is best because it is simplest.
    Last edited by laserlight; 01-26-2017 at 10:45 PM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. accessing structure members that are boolean pointers.
    By riely44 in forum C Programming
    Replies: 10
    Last Post: 12-08-2012, 07:43 PM
  2. Accessing array members
    By kkk in forum C Programming
    Replies: 1
    Last Post: 06-05-2011, 01:56 PM
  3. Accessing Structure Members
    By anndruu12 in forum C Programming
    Replies: 5
    Last Post: 12-02-2010, 02:37 AM
  4. accessing Class members
    By fizisyen in forum C++ Programming
    Replies: 3
    Last Post: 01-07-2004, 06:18 PM
  5. Accessing structure members
    By foniks munkee in forum C Programming
    Replies: 18
    Last Post: 02-13-2002, 03:06 PM

Tags for this Thread