C++ Pointer to Structures

Pointer: A pointer is a variable that stores the memory address of an object.

Structure: In C/C++, a structure is a user-defined data type. A structure defines a data type that may be used to combine objects of potentially multiple types into a single type.

A pointer variable may be made for both native (int, float, and double.) and user-defined types like structure. The structure pointer is defined as a pointer that refers to the address of the memory block containing a structure. 

Syntax of Structure To Pointer:

struct abc
{
   int value;
};
int main()
{
    struct abc p;
    struct abc*ptr = &p;
    return 0;
}

Example: To determine the area of a  Square or Rectangle using a pointer to structure approach

Code:

C++ Code

#include <iostream>
#include <stdio.h>
using namespace std;
struct area {
    int length;
    int breadth;
};

int main()
{
  area *ptr, a;
  ptr= &a;
  cout<<"Enter length : "<<endl;
  cin>>(*ptr).length;
  cout<<"Enter breadth : "<<endl;
  cin>>(*ptr).breadth;
  
  cout<<"Area is : "<<((*ptr).length)*((*ptr).breadth)<<endl;
  cout<<"Area is : "<<(ptr->length)*(ptr->breadth)<<endl; 
  //(*ptr).length is same as ptr->length (exactly same thing , 
  //just different denotations)
  cout<<"Area is m : "<<(a.length)*(a.breadth)<<endl;
  //a.length is same as (*ptr).length since ptr is pointing to the variable a

    return 0;
}

Output:

Enter length : 
2
Enter breadth : 
4
Area is: 8
Area is: 8
Area normally is: 8

Ptr: Pointer Variable & a: Normal Variable.

Special thanks to Naman Mathur for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article