Difference between -> and . in a struct?

前端 未结 7 1980
夕颜
夕颜 2020-12-13 10:09

If I have a struct like

struct account {
   int account_number;
};

Then what\'s the difference between doing

myAccount.acco         


        
相关标签:
7条回答
  • 2020-12-13 10:21

    -> is a pointer dereference and . accessor combined

    0 讨论(0)
  • printf("Book title: %s\n", book->subject); printf("Book code: %d\n", (*book).book_code);

    0 讨论(0)
  • 2020-12-13 10:28

    -> is a shorthand for (*x).field, where x is a pointer to a variable of type struct account, and field is a field in the struct, such as account_number.

    If you have a pointer to a struct, then saying

    accountp->account_number;
    

    is much more concise than

    (*accountp).account_number;
    
    0 讨论(0)
  • 2020-12-13 10:36

    If myAccount is a pointer, use this syntax:

    myAccount->account_number;
    

    If it's not, use this one instead:

    myAccount.account_number;
    
    0 讨论(0)
  • 2020-12-13 10:38

    You use . when you're dealing with variables. You use -> when you are dealing with pointers.

    For example:

    struct account {
       int account_number;
    };
    

    Declare a new variable of type struct account:

    struct account s;
    ...
    // initializing the variable
    s.account_number = 1;
    

    Declare a as a pointer to struct account:

    struct account *a;
    ...
    // initializing the variable
    a = &some_account;  // point the pointer to some_account
    a->account_number = 1; // modifying the value of account_number
    

    Using a->account_number = 1; is an alternate syntax for (*a).account_number = 1;

    I hope this helps.

    0 讨论(0)
  • yes you can use struct membrs both the ways...

    one is with DOt:(" . ")

    myAccount.account_number;
    

    anotherone is:(" -> ")

    (&myAccount)->account_number;
    
    0 讨论(0)
提交回复
热议问题