Pointer to a Structure

//Simple Program
struct Rectangle
    int length;
     int breadth;
int main()
   struct Rectangle r={10,5};
   struct Rectangle *p =&r;
    p.length=20;                         //compile time error bcz it is a pointer variable
   *p.length=20                         //compile time error bcz highest precedence is           //for  dot (.) operator so, first it will take (p.length)
//or we can simply write
     p->length=20;                     //for pointer variable use arrow(->)instead of    //dot(.)

note: size of pointer is 2 byte.
conclusion: for normal variable use (.)dot operator to acess.
eg: r.length =15;

for poiter variable use (->) arrow to acess
eg: p->length=20 or (*p).length=20

Now creating  a object dynamically in heap using pointer.
struct Rectangle{
int length;       // ---------------------------------- 2 byte (size)
int breadth;       // ---------------------------------- 2 byte (size )
}                          // ---------------------------------- 4 byte ( total size of struct)
int main(){
struct Rectangle *p;
//creating object in heap memory by using malloc()
p=(struct Rectangle *) malloc (sizeOf(struct Rectangle));
p->length =10;


Related post

Leave a Reply

Your email address will not be published. Required fields are marked *