pointer in the structure (struct) in c++ with examples

Image result for c++Going forward with this C/C++ programming language tutorial today we will know more about pointer.
Last time we have seen example of int pointer, but pointer can be of any datatype. It can even be struct. Lets see example of struct pointer here. If you do not know how to use struct then Read this C/C++ struct
#include <stdio.h>

struct
rectangle {
int
width;
int
length;
};


int
main() {
struct
rectangle r1;
r1.width = 10;
r1.length = 15;

struct
rectangle* r2;
r2 = &r1;
printf("Original width=%d, length=%d\n", (*r2).width, (*r2).length);

r1.width = 20;
r1.length = 25;
printf("r1 changed, width=%d, length=%d\n", (*r2).width, (*r2).length);

(*
r2).width = 5;
(*
r2).length = 10;
printf("*r2 changed, width=%d, length=%d\n", r1.width, r1.length);
return
0;
}


Run the example given above, we will understand output here. In main we have defined variable r1 of type struct rectangle 1st and declared pointer r2 which can store address of any struct rectangle. We have assigned address of r1 in that pointer. Now r1 is a variable and r2 is a pointer which has address of r1 hence if we change value of r1 then reading value from r2 will give changed value. Similarly if we change value through r2 value change then reading from r1 will give changed value.

See the example given above carefully. r2 is address(pointer) of r1, hence *r2 will give struct rectangle(*r2 and r1 is same. hence (*r2).width and r1.width is also same, changing one will be reflected on other.)
Important Note about pointer
1. shortcut for writing (*r2).width is r2->width. In program in place of (*r2).width, r2->width and in place of (*r2).length, r2->length can also be written. Replace this in program above and run to see output.
2. Declaring any variable any value have not assigned(as in int x;) defining means assigning value also(as in int x=1;) if you have just declared pointer and not assigned any address, then reading value from that pointer(using * as in *r2) will crash the program and it will give segmentation fault.