Structures: What Is A Structure?
Structures: What Is A Structure?
Structures
What is a Structure?
Structure is a collection of variables under a single name. Variables can be of
any type: int, float, char etc. The main difference between structure and array is
that arrays are collections of the same data type and structure is a collection of
variables under a single name.
In the above example, it is seen that variables of different types such as int and
float
are
grouped
in
a
single
structure
name
Customer.
Arrays behave in the same way, declaring structures does not mean that memory
is allocated. Structure declaration gives a skeleton or template for the structure.
After declaring the structure, the next step is to define a structure variable.
Page 2 of 6
Nested Structures
A structure can be nested inside another structure.
Stuct addr
{
int houseno;
char area[26];
Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 3 of 6
char city[26];
char state[26];
};
struct emp
{
int empno;
char name[26];
char desig[16];
addr address;
float basic;
};
emp worker ;
The structure emp h as been defined having several elements including a
structure address also. The elements address(of structure emp) is itself a
structure of type addr. While defining such structures, just make sure that innder
structure one defined before outer structure one defined before outer structures.
Page 4 of 6
Struct student
{
Int rollno;
char name[21];
float marks[5]; //array of 5 floats
};
students learner;
The above declared statement variable learner is of structure type student that
contains an elements which is a n array of 5 floats to store marks of a students in
5 different subjects.
Page 5 of 6
Passing entire structure to Functions
Passing entire structure makes the most sense when the structure is relatively
compact. The entire structure can be passed to the function both ways by value
and by reference. Passing by value is useful when the original values are not
to be changed and passing by reference is useful when original values are to
be changed.
User Defined Data Types
C++ allows you to define explicitly new data type name by using the keyword
typedef doses not actually create a new data class, rather it defines a new
name for an exiting type. This can increase the potablity of a program as only the
typedef statements would have to be changed . Using typedef can also aid in
self- documenting your code by allowing ddescriptive name for the standard data
type. The syntax of the typedef statement is
Typedef type name ;
Page 6 of 6