0% found this document useful (0 votes)
14 views

PART 9

The document provides a comprehensive overview of structures in the C programming language, detailing their definition, usage, initialization, and comparison. It also covers advanced topics such as arrays of structures, nested structures, self-referential structures, and the use of typedef and enum. Additionally, it discusses bit fields and unions, highlighting their differences and specific use cases in memory management.

Uploaded by

Sampurna prusty
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

PART 9

The document provides a comprehensive overview of structures in the C programming language, detailing their definition, usage, initialization, and comparison. It also covers advanced topics such as arrays of structures, nested structures, self-referential structures, and the use of typedef and enum. Additionally, it discusses bit fields and unions, highlighting their differences and specific use cases in memory management.

Uploaded by

Sampurna prusty
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Structures

Basics of Structures:
 Primary data types are used to hold a single value at a time. Arrays can be used to represent a group of
items that belongs to the same data type. If we want to represent different types of data items using a single
value (or) name then we can’t use an array.
 Fortunately ‘C’ supports a constructed data type known as structure , which is a method for packing
data of different types. The concept of a structure is similar to that of a record in many other languages.
 These files are called structure elements (or) members. Each member may belong to different types of
data types.

Eg: struct book_info


{
char title [20];
char author [20];
int pages;
float price;
};
Here, book_info is the name of the structure which hold the details of four fields namely title, author, pages
and price. We can declare the structure variables using tag name anywhere in the program.

Eg: struct book_info book1, book2, book3;


Now each one of the these variables has four members has specified by the structure. It is used to combine
both structure declaration and variable declaration in one statement as follows.
struct book _ info
{
char title [20];
char author [20];
int pages;
float price;
} book1, book2, book3;
Rules:
In defining a structure, we should follow the rules like
 The structure definition is terminated with a semi-colon.
 The structure name, field names must be valid ‘C’ identifiers.
 Each member in the structure is declared independently. The tag name can be used to declare structure
variables.
 Normally structure definitions appear at beginning of the program, before variables (or) function
declarations. It may also appear before the main() in such case the definition is global and can be used by
other functions.

Giving values to members:


 It is important to note that members of a structure themselves are not variables. They should be linked
to the structure variables in order to make them meaningful members. The link between a member and a
structure variable is established by using member operator ‘.’, which is also known as dot operator (or)
period.
 We can assign values to the members of a structure in a number of ways one method is directly
assigning values to the members.
Eg: strcpy (book1.title , “Let us C”);
strcpy (book1.author , “kanethkar”);
book1. pages = 343;
book1. price = 145.50;
We can also use scanf() to provide values to the members.

Eg: scanf (“%s”, book1.title);


scanf (“%s”, book1.author);
scanf (“%d %d”, book1.pages, book1.price);

Structure Initialization:
Like any other data type, a structure variable can be initialized. But ‘C’ language doesn’t permit the
initialization of individual structure members with in the structures. The initialization must be done only in the
variable declaration.
Eg:
struct account
{
int act _ no;
char act _ type [20];
char cus _ name [20];
float balance;
}S1 = {1001, “savings”, “Kumar”, 10000.00};
void main ( )
{
struct account S2 = {1002 “current”, “Raju”, 15000.00};
}

Comparison of Structure variable:


Two variables of the same structure type can be compared in the same way as ordinary variable.
Let us assume S1, S2 belong to the same structure. Then the following operations are valid.

Operator Meaning

S1 = S2 Assign S2 to S1.
S1==S2 Compare all members of S1 and S2 and return 1 if they are equal and
0 otherwise.
S1! = S2 Return 1 if all the members are not equal, 0 otherwise

Arrays of Structure:
We use structures to describe the format of a number of related variables. In some cases we need to
store the information belonging to number of structure variables. In such cases, we may declare an array of
structures where each element of the array representing a structure variable. For example,
Eg: struct marks;
{
int marks1;
int marks2;
int marks3;
}s [10];
By using above syntax we can store marks of 10 students.
We can also assign values at the time of declaration.
Eg: void main ( )
{
struct marks S[3] = {{30, 40, 25} {10, 20, 30,} {20, 30, 40}};
}
When we use Array of structures, while accessing a member we should specify the structure variable and its
subscript that is
S[0].marks1= 30;
S[0].marks2= 40;
S[0].marks3 = 25;

Arrays with in Structures:


‘C’ permits the use of array as structure members. We can use a single or multi dimensional arrays of
type int (or) float.
Eg: struct Student
{
int roll no;
char name[20];
int subject[3];
float avg;
};
Here, the member subject contains three elements subject [0], subject [1], subject [2]. These elements can be
accessed using appropriate subscripts.
Eg: s[3].subject [2].

Structures within Structures:


It means nesting of structures. Nesting of structures is permitted in ‘C’.
Eg: struct emp
{
int empno;
char name [20];
struct allowance
{
int da;
int hra;
int pf;
} s;
} e1,e2,e3;
Now, the ‘emp’ structure contains another structure alliance with these members. The members contained in
the inner structure can be refilled as
e1.s.da;
e1.s.hra;
e1.s.pf;
The inner structure can also have more than one variable. It also allows to use tag names to define inner
structure.
Eg: struct date
{
int day;
int month;
int year;
};
struct account
{
int act_no;
char act_type [20];
char cust_name [20];
float balance;
struct date last_payment;
};
Structures and Functions:
 ‘C’ supports the passing of structure values as arguments to functions. There are three methods by
which the values of a structure can be transferred from one function to other.
 The first method in to pass each member of the structure as an actual arguments of the function call. It
is in efficient when the structure size in large. In this a copy of entire structure is passed to the function.
Here any changes to the structure members will not reflect to the original structure.
 The third approach is to pass a structure by using call by reference i.e., a pointer to a structure is passed
as an argument. This method is more efficient as changes to the structure with in the function will in the
function will reflect the original structure.
 The general format of sending a copy of a structure to the called function is as follows.
function_name (structure-variable name);

Structures and Pointers:


struct inventory
{
char name [20];
int number;
float price;
}product [2], *ptr;
The above statement declares the product as an Array of two elements and ptr as a pointer of type struct
inventory.
ptr = product
This assignment assigns the address of 0th element of product to ptr. In this case the members can be accessed
by using ptr as follows.
ptr name
ptr number
ptr price
‘->’ is called an arrow operator {made of minus sign & greater than symbol}.
We can also use the following notation to access a structure member by using ptr.
(*ptr).name
(*ptr).number
(*ptr).price.

Self –referential Structures:-


It is sometimes desirable to include within a structure one member that is a pointer to the parent structure
type. In general terms , this can be expressed as
struct tag
{
member1;
member2;
:
struct tag *name;
};
Example:-
struct list
{
char item[40];
struct list * next;
};
Such structures are known as self-referential structures.
 Self-referential structures are very useful in applications that involve linked data structures such as linked
lists and trees.
 The basic idea in a linked data structure is that each component within the structure includes a pointer
indicating where the next component can be found.
 Self-referential structures are ideally suited for applications involving linked data structures. Each structure
will represent a single component within linked data structure. The self –referential pointer will indicate the
location of the next component.

typedef:
‘C’ supports a feature known as “Type definition” that allows users to define an identifier that would
represent an existing data type. The user defined data type identifier can later be used to declare variables. It
takes the general form
typedef type identifier;
Where type refers to an existing data type and “identifier” refers to the “new” name given to the data type. The
existing data type may belong to any class type, including the user defined ones, but not the data type. typedef
can’t create new type.

Some examples of the type definition are


typedef int units;
typedef float marks;
Here units symbolizes int, and marks symbolizes float.They can be used to declare variables as follows.
units batch1, batch2;
marks name1[50], name2[50];

batch1 and batch2 are declared as int variables and name1[50] and name2[50] are declared as floating point
array variables. The main advantage is that we can create meaningful data type names for increasing the
readability of the program.

enum:
Another user defined data type is enumerated data type provided by ANSI standard. It is defined as
follows
enum identifier {value1, value2,…………………..value n};
The “identifier” is a user defined enumerated data type which can be used to declare variables that can have
one of the values enclosed within the braces (known as enumeration constants). After this definition we can
declare variables to be this ‘new’ type as below.
enum identifier v1, v2,………….. vn.
The enumerated variable v1, v2, …………. vn can only have one of the values value1, value2, ……..valuen.
The assignments of the following types are valid.
V1= value3;
V5= value1;
The compiler automatically assigns integer digits beginning with 0 to all Enumeration constants. I.e., the
enumeration constant value1 is assigned 0, value2 is assigned 1 ……….
However, the automatic assignments can be over ridden by assigning values explicit to the enumeration
constants for example.
enum day { Monday = 1, Tuesday,Wednesday,Thursday,Friday,Sunday}.
Here, the constant Monday is assigned the value of 1. The remaining constants are assigned values that
increase successively by 1.
Bit Fields
Introduction
 C allow integer members to be stored into memory spaces smaller than the compiler would ordinarily
allow.
 These space-saving structure members are called bit fields, and their width in bits can be explicitly
declared.
 Bit fields are used in programs that must force a data structure to correspond to a fixed hardware
representation and are unlikely to be portable.
The syntax for declaring a bit field is as follows:
type_specifier declarator :constant_expression;
 A bit field declaration contains a type specifier followed by an optional declarator, a colon, a constant
integer expression that indicates the field width in bits, and a semicolon. A bit field declaration may not
use either of the type qualifiers, const or volatile.
 The C99 implementation supports the following types.
 int

 short, signed short, unsigned short

 char, signed char, unsigned char

 long, signed long, unsigned long

 long long, signed long long, unsigned long long

 In all implementations, the default integer type for a bit field is unsigned.
 In C language, when we assign a value that is out of range to a bit field, the low-order bit pattern is
preserved and the appropriate bits are assigned.
 Bit fields with a length of 0 must be unnamed. Unnamed bit fields cannot be referenced or initialized. A
zero-width bit field can cause the next field to be aligned on the next container boundary where the
container is the same size as the underlying type of the bit field.
 Bit fields are also subject to the align compiler option. Each of the align suboptions gives a different
set of alignment properties to the bit fields.
 The maximum bit field length is 64 bits. For portability, do not use bit fields greater than 32 bits in size.
 The following restrictions apply to bit fields. We cannot:
 Define an array of bit fields

 Take the address of a bit field

 Have a pointer to a bit field

 Have a reference to a bit field


The following structure has three bit-field members kingdom, phylum, and genus, occupying
12, 6, and 2 bits respectively:
struct taxonomy {
int kingdom : 12;
int phylum : 6;
int genus : 2;
};
Alignment of Bit Fields
If a series of bit fields does not add up to the size of an int, padding can take place. The amount of padding
is determined by the alignment characteristics of the members of the structure.
The following example demonstrates padding. Suppose that an int occupies 4 bytes. The example declares
the identifier kitchen to be of type struct on_off:
struct on_off {
unsigned light : 1;
unsigned toaster : 1;
int count; /* 4 bytes */
unsigned ac : 4;
unsigned : 4;
unsigned clock : 1;
unsigned : 0;
unsigned flag : 1;
} kitchen ;
The structure kitchen contains eight members totalling 16 bytes. The following table describes the storage
that each member occupies:
Member Name Storage Occupied

Light 1 bit

Toaster 1 bit

(padding -- 30 bits) To the next int boundary

Count The size of an int (4 bytes)

Ac 4 bits

(unnamed field) 4 bits


Member Name Storage Occupied

Clock 1 bit

(padding -- 23 bits) To the next int boundary (unnamed field)

Flag 1 bit

(padding -- 31 bits) To the next int boundary

All references to structure fields must be fully qualified. For instance, we cannot reference the second field
by toaster. We must reference this field by kitchen.toaster.
The following expression sets the light field to 1:
kitchen.light = 1;
When we assign to a bit field a value that is out of its range, the bit pattern is preserved and the appropriate
bits are assigned. The following expression sets the toaster field of the kitchen structure to 0 because
only the least significant bit is assigned to the toaster field:
kitchen.toaster = 2;
Unions
 These are a concept borrowed from structures and therefore follow the same syntax as that of structure.
However there is a major distinction between structure and a union in terms of storage. In structure each
member has its own storage location where as all the members of unions use the same location. This
implies that although a union may contain many members of different types, it can handle only one
member at a time.
 Ex: Like structure a union can be declared using the key word union
union student
{
int rollno;
char name[20];
float avg;
};
In the above declaration union contains three variables each with a different data type. We can use only one of
them at a time. This is due to the fact that only one location is allocated for a union variable. The compiler
allocates a memory to a union variable that is large enough to hold the largest variable type in the union. In the
above declaration the member rollno requires 2bytes, member name requires 20bytes and the member avg
requires 4bytes. Hence in this case the union variable is allocated with 20bytes of memory.

Important points regarding Union


 To access a union member we can use the same syntax that we use for structure members.
 Unions may be used in all places where a structure is allowed.
 A union may be a member of a structure , and a structure may be a member of union.
 Structures and unions may be freely mixed with arrays.
 A union variable can be initialized provided its storage class is either external or static.
 Only one member of a union can be assigned a value at any one time.
 Most compilers will accept an initial value for only one union member and they will assign this value to
the first member within the union.
Variable Length Argument in C

 Variable length argument is a feature that allows a function to receive any number of arguments. There are
situations where we want a function to handle variable number of arguments according to requirement.
Variable length arguments is an advanced concept in C language offered by c99 standard. In c89 standard,
fixed arguments only can be passed to the functions.
 When a function gets number of arguments that changes at run time, we can go for variable length
arguments.
 It is denoted as … (3 dots)
 stdarg.h header file should be included to make use of variable length argument functions.

You might also like