Structures in c++


Published on

Published in: Education
1 Comment
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Structures in c++

  1. 1. Page 1 of 6 StructuresWhat is a Structure?Structure is a collection of variables under a single name. Variables can be ofany type: int, float, char etc. The main difference between structure and array isthat arrays are collections of the same data type and structure is a collection ofvariables under a single name.How to declare and create a StructureDeclaring a Structure:The structure is declared by using the keyword struct followed by structure name,also called a tag. Then the structure members (variables) are defined with theirtype and variable names inside the open and close braces { and }. Finally, theclosed braces end with a semicolon denoted as ; following the statement. Theabove structure declaration is also called a Structure Specifier.Example:Three variables: custnum of type int, salary of type int, commission of type floatare structure members and the structure name is Customer. This structure isdeclared as follows:In the above example, it is seen that variables of different types such as int andfloat are grouped in a single structure name Customer.Arrays behave in the same way, declaring structures does not mean that memoryis allocated. Structure declaration gives a skeleton or template for the structure.After declaring the structure, the next step is to define a structure variable. Prepared By Sumit Kumar Gupta, PGT Computer Science
  2. 2. Page 2 of 6How to declare Structure Variable?This is similar to variable declaration. For variable declaration, data type isdefined followed by variable name. For structure variable declaration, the datatype is the name of the structure followed by the structure variable name.In the above example, structure variable cust1 is defined as:What happens when this is defined? When structure is defined, it allocates orreserves space in memory. The memory space allocated will be cumulative of alldefined structure members. In the above example, there are 3 structuremembers: custnum, salary and commission. Of these, two are of type in and oneis of type float. If integer space allocated by a system is 2 bytes and float fourbytes the above would allo9acter 2bytes for custnum, 2 bytes for salary and 4bytes for commission.How to access structure members in C++?To access structure members, the operator used is the dot operator denoted by(.). The dot operator for accessing structure members is used thusly:structure variable name.member nameFor example:A programmer wants to assign 2000 for the structure member salary in the aboveexample of structure Customer with structure variable cust1 this is written as:Nested StructuresA structure can be nested inside another structure.Stuct addr{int houseno;char area[26]; Prepared By Sumit Kumar Gupta, PGT Computer Science
  3. 3. Page 3 of 6char 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 astructure address also. The elements address(of structure emp) is itself astructure of type addr. While defining such structures, just make sure that innderstructure one defined before outer structure one defined before outer structures.Structure and ArraysThe structure and the array both are c++ derived data types. While arrays arecollections of analogous elements, structures assembles dissimilar elementsunder one roof.Array and structure both combined together to form complex data objects. Theremay be structures contained within an array; also there array element of astructure.Array of StructureTo declare 100- elements array of structure of type addraddr mem_addr[100];To create an array having structures emp typeEmp sales_emp[100];Above declaration to create an array sales_emp to store 100 structures of emptype. Prepared By Sumit Kumar Gupta, PGT Computer Science
  4. 4. Page 4 of 6Array Within StructuresA structure elements my be simple or complex . A complex structure may itselfbe a structure or any array. When a structure elements happens to be an array itis treated in the same way as array are treated. The only additional things to bekept in mind is that to access it, its structure name followed by a (.) and the nameis to be given. For example consider structure ;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 thatcontains an elements which is a n array of 5 floats to store marks of a students in5 different subjects.Passing Structures to FunctionIf you have a structure local to a function and you need to pass its values toanother function , then it can be achieved in two ways : (i) by passing individualstructure elements , and (ii) by passing the entire structure . Both the ways cabbe achieved by call by value as well as by call by reference method pa passingvariables.Passing Structure Elements to FunctionsWhen an elements of a structure is passed to a function , you are actuallypassing the value of that element to the function Therefore , it just like passing asimple variable. Consider following structureStruct date { short day; shot month; short year; } Bdate;` Prepared By Sumit Kumar Gupta, PGT Computer Science
  5. 5. Page 5 of 6Passing entire structure to FunctionsPassing entire structure makes the most sense when the structure is relativelycompact. The entire structure can be passed to the function both ways by valueand by reference. Passing by value is useful when the original values are notto be changed and passing by reference is useful when original values are tobe changed.User Defined Data Types C++ allows you to define explicitly new data type name by using the keywordtypedef doses not actually create a new data class, rather it defines a newname for an exiting type. This can increase the potablity of a program as only thetypedef statements would have to be changed . Using typedef can also aid inself- documenting your code by allowing ddescriptive name for the standard datatype. The syntax of the typedef statement isTypedef type name ;Use of typedef for declaring structuresThe typedef function is used to declare the alias name for the structure type.typedef structure result { } progress; results report1;progress report2in this above program segment the usage of typedef defines a structure resultand an alias name of the same structure as progress.The two structures report1 and report2 are declared accordingly of the sametype as result and progress are now alternative nomenclature for each other.Enumerated data typesIt is another way of defining data types. It includes all the probables list of valuesthat a data type can take. It has the following format for declaration;Enum struc-name {v1 v2 ,v3, v3,v4…..v n } Prepared By Sumit Kumar Gupta, PGT Computer Science
  6. 6. Page 6 of 6 Practice Question Paper1. What is a structure?2. Define arrays of structures?3. Differentiate between the following using examplesa. Simple structureb. multiple structure4. Explain the following with examplesa. Declaration of a structureb. Definition of a structure variablec. Accessing of a structure memberd. Initialization of a member within structures.e. Arrays of structures.f. Passing structures to functionsg. Use defined structure6. Explain the usage of type def for declaring structure .7.What are enumerated data type?8. What are symbolic constants?9. Define a structure for length and breadth of a rectangle of type float and refer the same as rect.10. Write a statement to assign a variable measure to length member of rect structure variable.11. The enumerated type is considered as an integer type . Comment on the factual concern of the statement.12. Write a program segment to declared and initialize an array of four structure with name of the student age and marks in three subjects. Prepared By Sumit Kumar Gupta, PGT Computer Science