x

C++ Data Structures

PREV     NEXT

What are data structures?

  • In C++, it allows you to define variables like arrays which allow you to merge many data items of the same kind and structure is another user defined data type that allows you to merge the data items of different kinds.
  • Structures are used to define a record for example you want to keep track of your employees in an organization.

You may want to track the information of the following attributes about each employee:-


  • Name
  • EmpID
  • Designation

How to define a structure?

While defining a structure you must use the struct statement as it defines a new data type with more than one member.

Let us have a look at the format:

  • In the above format the structure tag is optional and each member definition is a normal variable definition like int x; float y; or char c; or any other valid variable definition.
  • At the end of the structure definition before the semi colon you can specify one or more structure variables but that is also optional.

Let us have a look at the example on how to declare the Employee Structure:

How to access the structure members?

  • The structure members can be accessed by using the member access operator (.).
  • The operator is used between the structure variable and the structure member that we want to use.

Let us have a look at the example:

What are Structures as Function Arguments?

The structures can be passing as function arguments in the same way as you pass any other variable or pointer.


You would access the structure variables in the same way as we have accessed the structures in the above example:

What are Pointers to Structures?

The pointer to structures can be defined in the same way as we define the pointer to any other variable.

Let us have a look at the syntax:

In the above syntax, you can store the address of a structure variable in the above defined pointer variable and to find the address of a structure variable we will use the “&” operator before the structure name and to access the members of the structure by using the pointer you must use the

Operator like this:

struct_pointer -> Name;

Let us have a look at the example:



Like it? Please Spread the word!