C++ tutorial-C++ stucture


C++ structure

What is a structure?

A structure is a collection of variables. For instance, if you have a student structure then you will group the student number, student name, and sex together.

Creating and using a structure

To create a structure, you must use struct keyword followed by the name of the structure. Variables of the structure must be put in curly brackets. In the example below, we create a structure named student containing stnumber,stname, and stsex variables.


Example
#include<iostream>
 
struct student
{

  int stnumber;
  char *stname;
  char *stsex;
};

To use student structure, you must create an object by writing the name of structure followed by the name of object being created.
Example:
int main()
{
   student stu; //create object stu
   return 0;
}

You can initialize a structure object using initializer lists, as is done with arrays.

student stu={12,"Dara","Male"};

To set values to the variables of the structure, you must use the name of structure that has been declared followed by the names of thse variables.
Example:
#include<iostream>
 
struct student
{

  int stnumber;
  char *stname;
  char *stsex;
};

 
int main(){
  student stu;
  stu.stnumber=123;
  stu.stname="Channa";
  stu.stsex="Male";
  cout<<stu.stnumber<<" "<<stu.stname<<" "<<stu.stsex;
  return 0;
}

Pointers to structures

When you are using a pointer to a structure then you must use a -> instead of a dot to access its items.
Example:
student stu;
student *sp = &stu;
sp->stnumber = 123;

sp->stname="Channa";
st->stsex="male";

Passing structures to function

You can pass a structure object to function, as is done with a normal variable. In default, it is passed to function by value. You will use pointer or & operator to pass the structure to function by reference.

#include <iostream>
using namespace std;
struct student
{
  int stnumber;
  char *stname;
  char *stsex;
};
//pass structure to function by value
void printInfo(student stu){
  cout<<stu.stnumber<<" "<<stu.stname<<" "<<stu.stsex<<endl;;
}
//pass structure to function by reference
student getStudent(student *stu){
  stu->stnumber=123;
  stu->stname="hanna";
  stu->stsex="ale";
  return(*stu);
}
int main(){
  student stu;
  student s=getStudent(&stu);
  printInfo(s);
  return 0;
}


Comments




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.