pointer and structure

pointer with structure based on two different concept of C++, are follows

As we know, we can access the address of a variable by using pointer with another data type (int, float, char). Similarly by using pointer with structure, we can access address of structure-variable.

accessing structure-variable address

In this, we can print the address of structure-variable in two ways.

  • First by making the structure-variable direct a pointer-variable, such as-
struct {
Data member 1;
Data member 2;
Data member n;
} *structure-variable;

then

cout<<&structure_variable;// structure address will be print 
  •  Second by declare a pointer-variable and store the address in it, i.e. a new structure pointer-variable will declare. such as
  struct {
     member 1;
     member 2;
     member n;
} structure_variable,*pointer-variable;

First of all, we store the structure-variable address in pointer-variable-

ptr = &structure-variable;

then print the address-,

cout<<ptr; // structure_variable address will be print

As we know that we use dot operator to access structure members but in this, we access structure members using arrow operator (->), in this way you can say that in C++ you can have two types Can access any structure members from.

  • dot operator (.)
  • ‌arrow operator (->)

accessing members of a structure from dot operator is already mentioned in the structure. Here we are declaring the structure variable pointer-variable in the program below and accessing its members with the arrow-operator and also the address of the structure-variable has been printed-

accessing structure member using arrow operator

#include<iostream.h>
#include<conio.h>
#include<stdio.h>

void main()
{
  struct book  {                    // struct declaration inside main()
     int sr;
     char name[20];
     float price;
}x;
/
 book *vr;
 vr = &x;             // structure-pointer declaration

  clrscr();
  cout<<"Enter Serial No.: ";
  cin>>vr->sr;

  cout<<"Enter Book Name : ";
  gets(vr->name);

  cout<<"Enter Book Price: ";
  cin>>vr->price;

  cout<<"\nSerial No.: "<<vr->sr;

  cout<<"\nBook Name : "<<vr->name;

  cout<<"\nBook Price: "<<(*vr).price;               // accessing member using dot operator

  cout<<"\n\nmemory locaton is :"<<vr;             // display address of structure variable
  
getch();
}
OUTPUT:-
Enter Serial No.: 101
Enter Book Name : Science
Enter Book Price: 230.5

Serial No.: 101
Book Name : Science
Book Price: 230.5

memory locaton is :0x8ed7ffda

Because class is updated version of structure , so pointer with structure and pointer with class, both program will be same.

more about pointer


previous-Pointer in C++

next-Memory Management and Types