How to use struct pointer operators in accessing the struct members: ways on accessing struct members

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows 2003 Server Standard Edition

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Several way on accessing struct members in C++ program

To show: How to use struct pointer operators in accessing the struct elements

 

// Using the structure pointer operators to accessing structure elements...

#include <iostream>

using namespace std;

 

// define structure of Card with two elements

struct Card

{

char *face;

char *suit;

};

 

int main(void)

{

// declaring struct variables of type  Card

struct Card p;

struct Card *SPtr;

 

// assigning values to the struct members

p.face = "Ace";

p.suit = "Spades";

SPtr = &p;

 

cout<<"Accessing structure element styles"<<endl;

cout<<"----------------------------------"<<endl;

cout<<"Style #1-use p.face: "<<p.face<<" of "<<p.suit<<endl;

cout<<"Style #2-use Sptr->face: "<<SPtr->face<<" of "<<SPtr->suit<<endl;

cout<<"Style #3-use (*Sptr).face: "<<(*SPtr).face<<" of "<<(*SPtr).suit<<endl;

return 0;

}

 

Output example:

 

Accessing structure element styles

----------------------------------

Style #1-use p.face: Ace of Spades

Style #2-use Sptr->face: Ace of Spades

Style #3-use (*Sptr).face: Ace of Spades

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index