Pages

Tuesday, November 7, 2017

Easy tutorial for C / C ++ - struct 3 (pointer to struct)

Easy tutorial for C / C ++ - struct 3 (pointer to struct)

Pointer to struct :

- Struct can use pointers just like any other data type. The pointer is used points to the start address of the declared struct variable. The usage is as follows.

ex) t_Struct *pt ;

- 't_Struct' is the newly defined struct (data type) and 'pt' is the pointer variable.

- Let's look at how to access data through pointers to struct. Because the pointer points to the address, we put the '*' operator before the pointer for indirect reference. For struct, one thing to note is that the member variable access operator '.' (Priority problem with operators.)

- Because the precedence of the operator '.' is higher than the operator '*', you should use the '()' operator around the pointer as follows.

*pt.color    (x)
(*pt).color   (o)

- Another way is to use the '->' operator. For pointers to struct, you can use the '->' operator as follows to access member variables.

pt-> color

- Let's look at an example.

Example Code

#include <iostream>
using namespace std;

struct t_Struct{
   int num;
   char fruit[30];
   char color[30];
};

int main() {
     t_Struct strA = {7, "banana", "blue"};

     cout << " 1st results " << endl ;
     cout << " number = " << strA.num << endl ;
     cout << " fruit  = " << strA.fruit << endl ;
     cout << " color  = " << strA.color << endl ;
     cout << endl;

     t_Struct *pt;
     pt = &strA;
     cout << " 2nd results " << endl ;
     cout << " number = " << (*pt).num << endl ;
     cout << " fruit  = " << (*pt).fruit << endl ;
     cout << " color  = " << (*pt).color << endl ;
     cout << endl;

     cout << " 3rd results " << endl ;
     cout << " number = " << pt->num << endl ;
     cout << " fruit  = " << pt->fruit << endl ;
     cout << " color  = " << pt->color << endl ;
     cout << endl;
     return 0;
}

- We have declared a struct named 't_Struct'. We have defined the integer variable 'num', the string variables 'fruit' and 'color' as a member variable.

- In the main function, we have declared the struct variable 'strA' and initialized it with {7, "banana", "blue"}. And we accessed the member variable through the '.' operator and printed it.

- We have declare the pointer variable 'pt' and assigned the address value of the struct variable 'strA' to 'pt'.

- Struct pointer variable was used to output data of member variables. First, using the '.' operator "(* pt).", we will print the result. Second, we use '->' operator "pt->" for output.

results :

 1st results
 number = 7
 fruit  = banana
 color  = blue

 2nd results
 number = 7
 fruit  = banana
 color  = blue

 3rd results
 number = 7
 fruit  = banana
 color  = blue

- You can see that all the three give the same result.

No comments:

Post a Comment