UNIT-III
Structures
53. A structure is a collection of one or
more variables, possibly of different data types, grouped together under a
single name for convenient handling. A structure is a convenient way of
grouping several pieces of related information together.
Structure is user defined data type which is
used to store heterogeneous data under unique name. Keyword 'struct' is used to
declare structure.
The variables which are declared
inside the structure are called as 'members of structure'.
54.
Syntax of structure definition:
struct tag_name
{
data_type member_1;
data_type member_2;
data_type member_n;
};
55.
Defining a Structure(using typedef)
typedef defines and names a new type,
allowing its use throughout the program. typedefs usually occur just after the
#define and #include statements in a file.
Example structure definition.
typedef struct
{
char name[64];
char course[128];
int age;
int year;
} student;
This defines a new type student
variables of type student
56.
Declaring Stucture Variables:
The first way is to declare a
structure followed by structure definition like this :
struct structure_name
{
structure _member;
.....
}instance_1,instance_2,..instance_n;
In the second way, we can declare the
structure instance at a different location in our source code after structure
definition(in the main function).
Here is structure declaration syntax
:
struct struct_name
instance_1,instance_2 instance_n;
Example: struct student s;
57.
Accessing Members of a Structure
Each member of a structure can be
used just like a normal variable, but its name will be a bit longer. In the
above, member name of structure „s‟ will behave just like a normal array
of char, however we refer to it by the name
s.name
Here the dot is an operator which
selects a member from a structure(member operator). Where we have a pointer to
a structure we could dereference the pointer and then use dot as a member
selector. This method is a little clumsy to type. Since selecting a member from
a structure pointer happens frequently, it has its own operator -> which
acts as follows. Assume that st_ptr is a pointer to a structure of type
student, We would refer to the name member as
st_ptr -> name
58.
Structures and functions
A structure can be passed as a
function argument just like any other variable. This raises a few practical
issues.
A structure can be passed to a
function in 3 ways.
(i) Passing
individual members of the structure to a function.
(ii) Passing a
copy of the structure variable( Call by value).
(iii) Passing a structure by passing
its pointer to the structure.
59.
Nested structures(Structures within
Structures) :
Structures can be used as structures
within structures. It is also called as 'nesting of structures'.
Syntax:
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
- - - - - - - - - - -
- - - - - - - - - - -
<data-type> element n;
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
- - - - - - - - - - -
- - - - - - - - - - -
<data-type> element n;
}inner_struct_var;
}outer_struct_var;
60.
Arrays within Structures:
Sometimes, it is necessary to use
structure members with array.
Program :
#include <stdio.h>
#include <conio.h>
struct result
{
int rno, mrks[5];
char nm;
}res;
61.
Arrays of structures:
An array of structures for the
example is declared in the usual way: 100 books
struct book
{
char name[20];
char author[20];
int pages;
float price;
} struct student[100];
62.Self referential Structures
A structure can contain a pointer to
another structure of its own type, or even to itself. This is because a pointer
to a structure is not itself a structure, but merely a variable that holds the
address of a structure. Pointers to structures are quite invaluable, in fact, for
building data structures such as linked lists and trees.
A pointer to a structure type
variable is declared by a statement such as the following:
struct student *st_ptr;
63.
Applications of Structures
1. Complex numbers in mathematics
2. structures could be used to hold the
locations of points in multi-dimensional space
3. Apart from holding data, structures
can be used as members of other structures. Arrays of structures are possible,
and are a good way of storing lists of data with regular fields, such as databases.
4. Another possibility is a structure
whose fields include pointers to its own type. These can be used to build
chains (programmers call these linked lists), trees or other connected
structures.
UNIONS
64.
Union is user defined data type used
to stored data under unique variable name at single memory location. Union is
similar to that of structure. Syntax of union is similar to structure.
To declare union data type, 'union'
keyword is used.
Union holds value for one data type
which requires larger storage among their members.
Syntax:
union union_name
{
<data-type> element 1;
<data-type> element 2;
<data-type> element 3;
}union_variable;
65.
major difference between structure
and union is 'storage.' In structures, each member has its own storage
location, whereas all the members of union use the same location. Union
contains many members of different types, it can handle only one member at a
time.
66.
67.
68.
Enumerations
An enumeration is a data type
consisting of a set of named values that represent integral constants, known as
enumeration constants.
An enumeration also referred to as an
enumerated type because we must list (enumerate) each of the values in
creating a name for each of them. In addition to providing a way of defining
and grouping sets of integral constants, enumerations are useful for variables
that have a small number of possible values.
ENUM is closely related to the
#define preprocessor.
It allows you to define a list of
aliases which represent integer numbers. For example if you find yourself
coding something like:
#define MON 1
#define TUE 2
#define WED 3
You could use enum as below.
enum week { Mon=1, Tue, Wed, Thu, Fri
Sat, Sun} days;
or
enum escapes { BELL = '\a', BACKSPACE
= '\b', HTAB = '\t',
RETURN = '\r', NEWLINE = '\n', VTAB =
'\v' };
or
enum boolean { FALSE = 0, TRUE };
An advantage of enum over #define is
that it has scope This means that the variable (just like any other) is only visable
within the block it was declared within.
We can declare an enumeration type
separately from the definition of variables of that type.We can define an
enumeration data type and all variables that have that type in one statement
69.
Bit Fields
In addition to declarators for
members of a structure or union, a structure declarator can also be a specified
number of bits, called a "bit field." Its length is set off from the
declarator for the field name by a colon. A bit field is interpreted as an integral
type.
Bit Fields allow the packing of data in a
structure
FILE MANAGEMENT IN C
70.
A file is nothing but a place on the
disk where a group of related data is stored. Until here we read and write data
through console I/o functions scanf and printf,
which always use the keyboard /screen as the target place.
71
The basic file operation in ‘C’
Ø Naming a file
Ø Opening a file
Ø Reading data from a file
Ø Writing data to a file
Ø Closing
file
72
File handling functions in ‘C’
library
fopen( ) → creates a new life for
use/open existing file
fclose( ) → closes file
getc( ) → read a char from file
putc( ) →writes a char to file
fprintf →writes a set of data values
to a file
fscanf → reads a se of data values
from a file
getw( ) → reads an integer from a
file
putw( ) → writes an integer to a file
fseek( ) → sets the position to a
designed point in file
ftell( ) → sets the position to the
beginning of file
73
Text files
Text files store character data. A
text file can be thought of as a stream of characters that can be processed
sequentially
74
Binary files
As far as the operating system is
concerned, a binary file is no different to a text file. It is a collection of
bytes.
75.
Mode for opening a file
r →opens file for reading only
w → opens file for writing only
a → opens file for appending
(adding)data.
r+ → for both reading and writing at
the beginning only
w+ → after writing we may read the
file without closing and reopening
a+ → open a file in read and append
mode
ð When the mode is writing new
file is created (or) the contents are deleted, if the file is already existed.
ð When the mode is appending,
the file is opened and add the contents of new (or) new file also created, if
file does not exist.
ð When
the mode is reading, if the file existed then the file is opened
with the current contents safe otherwise an error occurs.
76.
Input/output operations on Files:
getc and putc functions: the simplest
file I/o functions are getc and putc.
ð „getc‟ is
used to read a char from a file
Example: c=getc(fp1);
ð „putc‟ is
used to write a char to a file
Example: putc(c1,fp1);
EOF – End of file (when EOF
encountered the reading / writing should be terminated)
77.
The getw and putw functions:
These are integer oriented functions.
These are similar to above functions and are used to read and write integer
values. These are useful when we deal with only integer data. The general
format is
putw (integer , fp);
getw(fp);
The fprintf and fscanf functions:
Until now, we handle one char/integer
at a time. But these functions handle a group of mixed data simultaneously.
Syntax of fprintf is
fprintf (fp, “control string”, list);
78.
ð fscanf is used
to read list of items from a file
ð fprintf is used to write a list of items
to a file.
79.
Error handling during I/o operations:
→ During I/o
operations on a file an error may occur. The error may be,
→ Trying to
read beyond the end-of-file
→ Device
overflow
→ Trying to
use a file that has not been opened.
→ If the modes
are not mentioned properly
→ Open a file
with invalid name
→ Try to write contents to a write
protected file
feof and ferror functions
help us to detect I/o errors in the file
ð feof
is used to test
an end of file condition . It takes a FILE pointer as its only argument and
returns a non zero integer value if all the data has been read, and returns
zero otherwise.
Example: if (feof(fp))
printf(“end of data”);
ð ferror
reports the
status of the file indicated . It also takes a FILE pointer as its argument and
returns a non zero integer if an error has been detected up to that point,
during processing , otherwise returns o.
if (ferror(fp)!=0)
printf(“an error has ocured”);
This prints an error message, if
reading is not successful.
80.
Random Access to files:
Until now we read and write data to a
file sequentially. In some situations we need only a particular part of file
and not other parts. This can be done with the help of fseek, ftell,
rewind functions.
81.
ftell: It takes a file pointer and returns
number of type long , that corresponds to the current position. This is useful
in saving the current position of file.
Example: n=ftell(fp);
n’ would give the relative offset (in
bytes) of current position. i.e., n bytes have all ready been
read/ write.
rewind: It takes file pointer and resets the
position to the start of the file.
Example: rewind(fp);
fseek: This function is used to move file
position to a desired location within file.
Syntax: fseek (file pointer, offset,
position)
Example: fseek (Fp1, 0L,); → go to
the beginning
Fseek(fp1,m,1) → go forward by m
bytes
Position 0 ─ beginning
1─ current position
2─ end of file
Offset Positive ─ move forward
Negative ─move backward
OL ─ no more (stay)
If the fseek file
operation is successful, it returns 0 else returns -1 (error
occur)
82.
Command line arguments:
As we know „main‟
function is marked the beginning of the program. This „main‟ can
take two arguments argc and argv and information
contained in the command line is passed on to the program through these
arguments.
→ Argc – is an
argument counter (counts the No. of arguments on the command line)
→ Argv – is am argument rector (array
of char, pointers which points command line)
83.
Dynamic Memory Allocation
Dynamic allocation is a pretty unique
feature to C (amongst high level languages). It enables us to create data types
and structures of any size and length to suit our programs need within the
program.
84.
Malloc, Sizeof, and Free
The Function malloc is most commonly
used to attempt to ``grab'' a continuous portion of memory. It is defined by:
void *malloc(size_t number_of_bytes)
85.
Calloc and Realloc
There are two additional memory
allocation functions, Calloc() and Realloc(). Their prototypes are given below:
void *calloc(size_t num_elements,
size_t element_size};
void *realloc( void *ptr, size_t
new_size);
Realloc is a function which attempts
to change the size of a previous allocated block of memory
malloc does not initialize memory (to
zero) in any way. If you wish to initialize memory then use
calloc. Calloc there is slightly more computationally expensive but,
occasionally, more convenient than malloc