Structures and Arrays

Strutures are user defiened data types, whereas arrays are derived data types. While an array is a collection of nalogous elements elements, a structure assembles dissimilar elements under one roof. thus both arrays and structures allow several values to be treated together as a single data object.

int a[]={10,20,30,40,50}; // array are elements of the same type (int)

student stud1={2, "Rahul",12, 67.00, 'A'}; // structure elements are of different types

Arrays of structures

Using arrays of structures is similar to using arrays of anything else. When structures are present within an array you have an array of structures. To declare an array of structures, you must define a structure and then declare an array variable of that type. For instance:

struct item

{

int itemno;

char desc[20];

float cost;

};

item it[50]; // array of the structure item

The above declaration defines an array of structure it[50] of type item.This declaration creates 50 sets of variables that are organized as defined in the structure item.

To access a specific structure, the structure is indexed. To print the itemno of structure 10:

cout<<it[9].itemno;

Passing Structures to Functions

A structure can also be passed as an argument to a function. Passing a structure is just like passing a normal variable. In the prototye and the formal parameter list, the structure tag followed by the variable name is used for passing stuctures as arguments to functions. when a structure is passed as an argument, each member of the structure is copied from the actual parameters to the formal paramenters of the function.

A structure can be declared in two ways: globally and locally.

A global structue has a global scope and is accessible to all the functions within the C++ program. It is declared outside all the functions of the program.

A local strucutre has a local scope and is accesable only to the functions inside which it is declared.

Passing Structure elements to Functions

When an element of a structure is passed to a function, its value is passed to that function. Consider the structure date:

struct date

{

short int dd;

short int mm;

short int yy;

} J_date;

Individual elements of the structure can be passed as follows:

test(J_date.dd, J_date.mm, J_date.yy);

The functin call given above invokes a function test() by passing values of the individual structure elements of the structure date.

HOME LEARN C++

PREVIOUS NEXT