pointer with structure in C++ based on two different concepts are followed,
As we know, we can access the address of a variable by using a pointer with another data type (int, float, chat) Similarly, by using a pointer with a structure in C++, we can access the address of structure-variable.
accessing structure address in C++
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 declaring 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-,
फिर address print करने के लिए -,
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-
Pointer with structure program in C++
#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
struct book { // struct declaration inside main()
int sr;
char name[20];
float price;
}x;
/
book *vr;
vr = &x; // structure-pointer declaration
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
return 0;
}
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 location is :0x8ed7ffda
because a class is an updated version of the structure, so pointer with structure and pointer with class, both program will be the same.
more about pointer
previous- Pointer in C++
Next- Memory allocation in C++