DSA 1.20 : pointer to structure


Tue Mar 07 2023 13:52:21 GMT+0000 (Coordinated Universal Time)

Saved by @saakshi #c++

#include <iostream>
using namespace std;

struct rectangle
  int length;
  int breadth;

struct rectangle *fun()
  struct rectangle *p;
  p = new rectangle;
  //p= (struct rectangle *)malloc(sizeof(struct rectangle));
  p->length = 15;
  p->breadth = 7;
  return p;

int main()
  struct rectangle *ptr = fun();
  cout << "length : "<<ptr->length<<endl<<"breadth : "<< ptr->breadth<<endl;
  return 0;

this demonstrates how a function can return a pointer to an object created inside a heap memory that can be accessed using main function also it can be accessed by any function if that pointer is available.