C ++ में pointer with structure दो concept पर आधारित है –
- C++ pointer
- C++ structure
जैसा कि हम जानते हैं, हम एक pointer से एक variable का address access कर सकते हैं इसी तरह, C ++ में एक structure के साथ एक pointer-variable का प्रयोग करके, हम structure -variable के address को access कर सकते हैं।
accessing structure address in C++
इसमें हम structure के address को दो तरह से print करेंगे –
सबसे पहले structure -variable को एक pointer -variable declare करके , जैसे कि-
struct {
data member 1;
data member 2;
data member n;
} *structure-variable;
Then, फिर
cout<<&structure-variable;// structure address will be print
second pointer -variable declare करके और उसमें address को store करके, यानी एक नया structure pointer -variable declare करके। जैसे कि
struct {
member 1;
member 2;
member n;
} structure_variable,*pointer-variable;
सबसे पहले, हम pointer -variable में structure -variable के address को store करते हैं –
ptr = &structure-variable;
फिर address print करने के लिए -,
cout<<ptr; // structure-variable address will be print
ध्यान दें , यहाँ पर दूसरा तरीका ही सही होगा। क्योंकि यह address को store करने के साथ उसे print भी कर रहा है जिससे हम इस address को manipulate भी कर सकते हैं जबकि पहले वाले तरीके में यह संभव नहीं होगा।
जैसा कि हम जानते हैं कि हम structure – members को dot operator से access किया जाता है लेकिन इसमें हम arrow operator (->) का उपयोग structure -member को access करते हैं। इस तरह से आप कह सकते हैं कि C ++ में आप दो प्रकार से किसी structure -member को access कर सकते हैं।
- dot operator
- arrow operator
dot operator से structure members को access करना पहले ही structure में बताया गया है।
यहां हम नीचे दिए गए Program में, structure variable x और structure pointer variable *vr declare किये गए हैं जहाँ पर members pointer variable *vr से arrow-operator का प्रयोग करके access किया गया है और साथ ही structure variable x का address भी access किया गया है –
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
क्योंकि एक class structure का updated version है इसलिए pointer with structure और pointer with class, दोनों लगभग समान होंगे।
more about pointer
previous- Pointer in C++
next- memory allocation in C++