Professional Documents
Culture Documents
STRUCTURES
6.1.1. Introduction
^ ^,fmCtUre is a User defined data type- A structure is a combination of several erent previously
defined data types, including other structures we have defined
> A structure is a grouping of related data in a way convenient to the programmer or
user of the program.
> A structure is a collection of variables of different types. Structures are sometimes
referred to as Abstract Data Types, (ADTs).
> Variables in a struct are called members or fields, and are accessed by their
J
name.
> The size of a structure is the sum of the sizes of all the variables it holds The
assignment operator with the structure declaration can not be used
A structure is a convenient method of handling a group of related data items of
different data types.
structure member n;
}struct_var_nm;
F.-xamnle ----------------------------------------------------------- --------------------------
int mo [5]; struct item_mst {
int mo;
char nm[50];
lit; —■ ----------------
struct Student {
int Rollno;
int Subject, I Brackets delimit gtnlcture members declaration float Marks; '
); structure members
In this example,
Rollno 2 bytes
Subject 2 bytes
Marks 4 bytes
Student structure will take total 8 bytes in the memory.
6.1.4. Variables Initialization
All external and static variables, including structures, which are not explicitly
initialised by the programmer, are automatically initialised by the system to zero.
In traditional C, only external and static variables can be initialised. ANSI C allows
automatic variables, including structures, to be initialised as well.
The syntax for initialising structures is similar to that for initialising arrays. A structure
variable in a declaration can be initialised by following it with an equal sign and a list
of constants contained within braces. If not enough values are used to assign all the
members of the structure, the remaining members are assigned the value zero by
default. Some examples are:
1) Card c = {13, ‘h’}; /* the king of hearts */
2) Complex a[3][3] = {
{{1.0,-0.1}, {2.0, 0.2}, {3.0, 0.3}},
{{4.0,-0.4}, {5.0, 0.5}, {6.0, 0.6}}, .
}; /* a[2][] is assigned zeroes */
3) struct fruit frt = {“plum”, 150};
4) struct home_address {
char * street; char
*city_and_state; long
zip_code;
} address = {“87 West Street”, “Aspen, Colorado”, 80526};
5) struct home_address previous_address = {0};
The last example illustrates a convenient way to initialise all members of a structure to
have value zero. It causes pointer members to be initialised with the pointer value
NULL and array members to have their elements initialised to zero.
Rules for Initializing Structures
1) We cannot initialize individual members inside the structure template.
2) The order of values enclosed in braces must match the order of members in the
structure definition.
3) It is permitted to have a partial initialization. We can initialize only the first few
members and leave the remaining blank. The uninitialized members should be only
at the end of the list.
4) The uninitialized members will be assigned default values as follows:
i) Zero for integer and floating point numbers.
ii) ‘\0’ for characters and strings.
The first component of above expression involving the dot operator is the name of the
specific structure variable(part2), not the name of the structure definition(part).
The variable name must be used to distinguish one variable from another, such as parti,
part2 and so on, as shown in figure 6.1.
Program 2: To calculate the student-wise totals and store them as a part of the
structure.
#include <stdio.h>
#include <conio.h>
struct marks {
int subl; int sub2;
The structure variable-identifier is separated from element-identifier by a dot (.). The dot
here is known as the direct selection operator, which is a postfix operator at
precedence level 1 in the precedence table.
For example, consider the following statement
part2.modelnumer=3884;
The first component of above expression involving the dot operator is the name of the
specific structure variable(part2), not the name of the structure definition(part).
The variable name must be used to distinguish one variable from another, such as parti,
part2 and so on, as shown in figure 6.1.
y modelnumber ^
partnumber
pnce
^ modelnumber y
partnumber
^ modelnumber ^
partnumber
part2. modelnumber
Operator
Explanation: In the program, a four-member structure is declared, the fourth one for
keeping the student-totals.
Note: A member name can be any valid C name and can be the same as an existing
structure variable name.
One can also apply increment and decrement operators to numeric type members.
Consider the following code segment to understand the increment and decrement
operators: student 1 ,number++;
++student 1 .number;
The precedence of the member operator is higher than all arithmetic and relational
operators and therefore no parentheses are required.
The typedef feature allows users to define new data types that are equivalent to existing
data types.
Once a user-defined data type has been established, then new variables, arrays,
structures and so on, can be declared in terms of this new data type.
int main()
{
weight apples = {200.75,145.5,100.25}; weight
pears = {150.50,125,50}; weight mangoes =
{1000, 567.25, 360.25}; clrscrQ;
printf( \n\n apples: big %7.2fkg, medium %7.2fkg,
small %7-2fkg",apples.big,apples.medium,apples.small);
printf("\n\n pears: big %7.2fkg, medium %7.2fkg, small %7.2fkg", pears.big,
pears.medium, pears.small); ’
printf("\n\n mangoes:' big %7.2fkg, medium %7.2fkg, small %7.2fkg",
mangoes.big, mangoes.medium, mangoes);
return 0;
}
| DOSBai 8J4. Cpuspeed: man100X gete, Ranestap 0, Praga* TC
scanf("%c", &test);
if(tolower(test) ==
'n') break;
printf("\nEnter the name of the horse:");
scanf("%s", My_horses[hcount].name); /* Read the horse’s name*/
printf("\nHow old is %s?", My_horses[hcount].name);
scanf("%d", &My_horses[hcount].age); /*Read the horse’s age */
printf("\nHow high is %s (in hands)?", My_horses[hcount].name);
/*Read the horse’s height*/
scanf("%d", &My_horses[hcount].height);
printf("\nWho is %s's father?", My_horses[hcount].name);
/* Get the father’s name */
scanf(" %s", My_horses[hcount].father);
printf("\nWho is %s's mother?", My_horses[hcount].name);
/* Get the mother’s name */
scanf("%s", My_horses[hcount] .mother);
}
Output
Program 9: To declare the array data type within a structure and to initialize
some of the structures and to display the contents of the structures.
#define MAX 5
#include<stdio.h>
main()
{
struct student}
char name[20];
long int rollno;
int age; .
char sex; •
float height; float weight;
};
static struct student class [MAX] = {
{"ravi", 91001, 25, 'M', 175.55, 56.7},
{"radha", 91002, 26, 'F, 167.22, 67.7},
{"kumari", 91003, 25, 'F, 180.2, 80.8},
{"sekar", 91004, 24, 'M\ 167.8,40.0}
};
int i;
Note: In older version, the C compilers will not permit Programmer to copy or compare
the two structures as whole. One has to copy or compare as member by member but the
latest version allows one to copy or compare any forms.
While using structure pointers, we should take care of the precedence of operators.
The operators and V, and () and [] enjoy the highest priority among the operators.
They bind very tightly with their operands.
6.1.13. Structures and Functions
A function decomposes a complex program into a simpler one. It is therefore a very
powerful tool in C programming. It is possible to pass structure to a function as a single
variable instead of passing each member of the structure as an actual argument of the
function call which is unmanageable and insufficient when the structure size becomes
large.
6.2. UNION
6.2.1. Definition
A derived data type, whose members share the same storage space, the members of
a union can be of any type and the number of bytes used to store a union must be at
least enough to hold the largest member.
Unions contain two or more data types. Only one member, and thus one data type,
can be referenced at a time. It is the programmer’s responsibility to ensure that the
data in a union is referenced with the proper data type and this is the weakness of
using union compared to struct.
Syntax:
union union_name
{
<data_type> memberl <data_type> member2
. <data_type> membern
}
For example, following is a union declaration:
union sample {
int p; float q;
};
Indicates that sample is a union type with members’ int p and float q. The union
definition normally precedes the main() in a program so the definition can be used to
declare variables in all the program’s functions.
Only a value with same type of the first union member can be used to initialize
union in declaration part.
Memory space required for defining a variable of the union is max(sizeof(member
1), sizeof(member2)... sizeof(membem),).
Ways of Union Variable Declaration
Like structures, the C language also provides two ways to declare a union: , , ,
1) Tagged Union: The first way to declare a union is to use tagged union. A tagged
union can be used to define variables, arguments, and return types.
Syntax: The syntax for declaring a tagged union is:
union MIXTYPES {
Field list
For example,
union MIXTYPES { '
char
cVar; int
iVar;
float
fVar;
double
dVar;
};
The tagged union starts with the keyword union. The next element in the
declaration is tag. The tag is the identifier for the union, and will be used to
declare variable, arguments of the functions, and return types for the functions.
If we conclude the union declaration with semicolon after the closing brace, no
variables are defined. In this case, the union is simply a type template with no
associated storage.
2) Type-Defined Union: The more powerful way to declare a union is by using
type definition typedef.
Syntax: The syntax for declaring a type-defined union is:
typedef union { '
Field list
} TYPE;
For example,
typedef unien
{
char cVar; int
iVar; float
fVar; double
dVar;
} MIXTYPES; -
Memory Map
However, the character value is stored in first byte, integer value in first two bytes,
float value in first four bytes, and double value in all the eight bytes.
memberN;
} variable 1, variable 2, variable 3,..., variableX;
Accessing Union Members
For accessing members of, say, variable 1 to N of the union tag_name, the
following constructs are used:
variablel.memberl
variable2.member2
variableX.memberN
Only a member that exists at the particular instance in storage should be accessed.
variableX.memberN = constant;
Where, X is any value 1 to X and N is any value 1 to N.
Program 12: Illustrates the initialisation of a member in a union.
#include<stdio.h>
#include<conio.h>
union test /* declaration of union */
{ - int i; /* integer member */
char c; /* character member */
}var; /* variable */
int main() }
{ /* initialising integer member */
var.i = 65; /* output integer member */
printf("\n var.i = %d", var.i); /* output character member */
printf("\n var.c = %c", var.c);
return 0;
Output
Explanation
The figure 6.5 for the storage location of union test:
Bit _
position
15 14 13 12 11 10 9 8 7
0 0 0 0 0 0 0
char c
inti ■
Figure 6.5 shows the storage location of union test. The location has two bytes because
the largest member in the union test is an integer named ‘i\ The other member, ‘c\ being
a character, occupies eight bits from bit 0 to bit 7. The integer member T is assigned the
value ‘65’. Hence, this value in binary form is stored in bits 0 to 15. So when printf() is
executed, the value 65 for T is printed on the screen. But the member ‘c’ has not been
assigned any value.
Therefore, the existing value of 65 in the referred storage location is taken when the
printf() for the member ‘char c’ is executed. Referring to the ASCII table, the
equivalent symbol for the decimal value 65 is ‘A’. Thus, when the second printf() is
executed, the output is ‘A’.
Explanation: This example demonstrates the structure and basic operation of a union.
Programmer declares the union Ul as follows: union u_example { ■ float decval; int
pnum; double my_value;
} Ul;
The three members of the union are of different types and they each require a different
amount of storage (assuming your compiler assigns 2 bytes to variables of type int).
With the assignment statements, you assign a value to each of the members of the
union instance Ul in turn:
Ul.my_value = 125.5;
Ul.pnum =10;
Ul.decval = 1000.5f;
Note: One can reference each member of the union in the same way as you do
members of a structure.
The next two statements output each of the three member values, the size of the union
Ul, and the size of each of its members. You get this output (or something close if your
machine assigns 4 bytes to variables of type int): decval = 1000.500000 pnum = 8192
my_value = 125.50016 U1 size = 8
decval size = 4 pnum size = 2 my_value size = 8
Last variable that was assigned a value is correct, and the other two have been
corrupted. This is to be expected, because they all share the same memory space. The
second thing to notice is how little the member my_value has been corrupted. This is
because only the least significant part of my_value is being modified.
In a practical situation, such a small error could easily be overlooked, but the ultimate
consequences could be terrible. You need to take great care when using unions that you
are not using invalid data.
Note: You can see from the output of the sizes of the union and its members that the
size of the union is the same as the size of the largest member.
#include <stdio.h>
#include <conio.h> struct Distance { int feet; float
inch;
} distance 1 ,distance2,sum;
main(){
printf("Enter information for First distance\n");
printf("Enter feet: ");
scanf("%d",&distancel.feet);
printf("Enter inch: ");
scanf(" %{'" ,&distance 1 .inch);
printf("\nEnter infromation for second distanceW);
printf("Enter feet: ");
scanf("%d",&distance2.feet);
printf("Enter inch: ");
scanf("%f',&distance2.inch);
sum.feet=distance 1 ,feet+distance2.feet;
sum.inch=distance 1 ,inch+distance2.inch;
main(){
complex numberl,number2,temp;
printf("For 1st complex number \n");
printf("Enter real and imaginary respectively:\n");
scanf(" %f%f' ,&number 1 .realnumber,&number 1 .imaginary);
printf("\nFor 2nd complex number \n");
printf("Enter real and imaginary respectively:\n");
scanf("%f%f',&number2.realnumber,&number2.imaginary);
temp=add(number 1 ,number2);
printf("Sum=%. lf+%. lfi",temp.realnumber,temp.imaginary);
getchO;
}
complex add(complex number 1,complex number2){
complex temp;
temp.realnumber=numberl.realnumber+number2.realnumber;
temp.imaginary=numberl.imaginary+number2.imaginary;
retum(temp);
}
Output __
* G\Users\pravesh\Deslrtop\To\VTU.exe ' ‘ E3 I®
6) Explain STSTw between pointers to arrays and arrays of pointers. Make-up an example
Is toe any difference between an array and a pointer? What does it mean to say an array is the same
7)
as a pointer to the array?
8) What are some purposes for unions?
9) What do you mean by the following terms.
i) Nested structure
ii) Self referential structure
10) When do we use the following?
i) Bit fields
ii) The sizeof operator
11) What is wrong with the following code? Trace and correct the code.
struct •¥
{ : int month: char zodiacsign[15];
}sign = 10 , "Libra";
int main()
{
union a {
int i;
char ch[2];
1;
union a u;
u.ch[0] = 3;
u.ch[l] = 2;
printf("%d, %d, %d\n", u.ch[0], u.ch[l], u.i);
return 0;
}
14) What will be the output of the program?
#include<stdio.h>
int main()
{
union var
{
int a, b;
};
union var v;
v.a=10;
v.b=20;
printf("%d\n", v.a); return 0;
15) What will be the output of the program?
#include<stdio.h>
int main()
{
struct value
{
int bitl: 1; '
int bit3:4; int bit4:4;
}bit={ 1, 2, 13};
printf("%d, %d, %d\n", bit.bitl, bit.bit3, bit.bit4);
return 0;
’
}
16) What will be the output of the program in 16 bit platform (Turbo C under DOS) 9
#mclude<stdio.h>
’
' int main()
{
struct value {
int bitl: 1;
int bit3:4;
int bit4:4;
}bit;
printf("%d\n", sizeof(bit)); return 0;
}
17) What will be the output of the program?
#include<stdio.h> int main()
{
enum days {MON=-l, TUE, WED=6, THU, FRI, SAT}-
printf("%d, %d, %d, %d, %d, %d\n", MON, TUE, WED,’ THU FRI SAT)- return 0;
’’’