Structure is a collection of DISSIMILAR kinds of data elements store at CONTINUES memory locations. In this article, you'll learn about structures in C++ programming; what is it, how to define it and use it in your program.
Syntax of Declaration A Structure:-
The struct keyword defines a structure type followed by an identifier (name of the structure).
Then inside the curly braces, you can declare one or more members (declare variables inside curly braces) of that structure. For example:
struct Person { char name[50]; int age; float salary; };
Here a structure person is defined which has three members: name, age and salary.
When a structure is created, no memory is allocated.
The structure definition is only the blueprint for the creating of variables. You can imagine it as a datatype. When you define an integer as below:
int foo;
The int specifies that, variable foo can hold integer element only. Similarly, structure definition only specifies that, what property a structure variable holds when it is defined.
Note::Remember to end the declaration with a semicolon(;)
#include<stdio.h> #include<string.h> typedef struct student{ int roll_num; char name[128]; } student_t; void print_struct(student_t*s){ printf("Roll num:%d,name:%s\n",s->roll_num,s->name); } int main(){ student_ts1,s2; s1.roll_num=4; strcpy(s1.name,"ram"); s2=s1; //Contents ofs1 are not affected as deep copy is performed on an array s2.name[0]='R'; s2.name[1]='A'; s2.name[2]='M'; print_struct(&s1); print_struct(&s2); return 0; }
Output:
Roll num:4,name: ram Roll num:4,name: RAM
Struct keyword is used to define a structure. Struct defines a new data type which is a collection of primary and derived datat ypes.
Syntax:
struct [structure_tag] { //member variable 1 //member variable 2 //member variable 3 ... }[structure_variables];
As you can see in the syntax above, we start with the struct keyword, then it's optional to provide your structure a name, we suggest you to give it a name, then inside the curly braces, we have to mention all the member variables, which are nothing but normal C language variables of different types like int, float, array etc.
After the closing curly brace, we can specify one or more structure variables, again this is optional.
The members of structure variable is accessed using a dot (.) operator.
Suppose, you want to access age
of structure variable bill
and assign it 50 to it. You can
perform this task by using following code below:
bill.age=50;
#include<iostream> #include<cstring> using namespace std; struct student { string name; int roll_no; }; int main(){ struct student stud={"Sam",1}; struct student * ptr; ptr=&stud; cout<< stud.name<< stud.roll_no<< endl; cout << ptr->name<< ptr->roll_no<< endl; return0; }
struct student*ptr;
-We declared 'ptr' as a pointer to the structure student.
ptr = &stud;
We made our pointer ptr to point to the structure variable stud. Thus,'ptr'now stores the address of the structure variable 'stud'.