I have heard that "C++ begins where C ends,,, LETS MOVE ON... Following program shows how to access struct which contains pointer to char,array,array of pointer and pointer to struct. simple program, access 'struct s' via pointer 'p1' Accessing done in sequential manner(see comments in bold letters) , easy to track and understand. #include<iostream> #include<cstring> using namespace std; struct l { char *i; int j; int la[2]; //array of integer int *lp[2]; //array of pointer }; struct s { char *m; struct l *k; //pointer to struct l int sa[2]; //array of integer int *sp[2]; //array of pointer }; int main() { struct s one; struct s *p1 = &one; /** Access struct via pointer**/ /** 1st variable in struct s i.e char *m **/ p1->m = new char; *p1->m = 'k'; cout<<"m="<<*p1->m<<endl; /** another method**/ p1->m = new (nothrow) char; if (p1->m == 0) cout<<"errr"<<endl; *p1->m = 'l'; cout<<"m="<<*p1->m<<endl; /** 2nd variable of struct s: struct l *k **/ p1->k = new l; p1->k->i = new char; // seg fault if u miss this *p1->k->i = 'k'; cout<<"i="<<*p1->k->i<<endl; /** ptr_stru ->ptr_stru -> arry **/ for (int i=0;i<2;i++) p1->k->la[i] = i; for(int i=0; i<2;i++) cout<<"la="<<p1->k->la[i]<<endl; /** stru - stru - arry_of_ptr **/ for (int i=0;i<2;i++) { p1->k->lp[i] = new int; *p1->k->lp[i] = i; } for (int i=0;i<2;i++) cout<<"kp="<<*p1->k->lp[i]<<endl; /** 3rd variable of struct s: int sa[2] **/ for (int i=0;i<2;i++) p1->sa[i] =i ; for (int i=0;i<2;i++) cout<<"sa="<<p1->sa[i]<<endl; /** 4th variable of struct s: int *sp[2] **/ for (int i=0;i<2;i++) { p1->sp[i] = new int; *p1->sp[i] = i; } for (int i=0;i<2;i++) cout<<"sp="<<*p1->sp[i]<<endl; return 0; } OUTPUT: m=k m=l /**access variables of struct l via pointer 'k'**/ i=k la=0 la=1 kp=0 kp=1 /** access array and array of pointers **/ sa=0 sa=1 sp=0 sp=1
Struct : All about accessing
September 12, 2011 by manu
Leave a comment