SlideShare a Scribd company logo
1 of 65
Download to read offline
400 File & Data Structure
✞
1 struct s {
int id1; //4 bytes for data
3 int id2; //4 bytes for data
};// total size will be equal to sum of all
5 // bytes , upward rounded off to , multiple
//to size of largest structure member.
✌
✆
✞
#include <stdio.h>
2
struct s {
4 int id1;
int id2;
6 }; // Total 8 bytes rounded up to
// 4*2=8 bytes is size of s
8
int main () {
10 printf("Size of Structure s in bytes is ");
printf("%d.n", sizeof(struct s));
12 return 0;
}
✌
✆
✞
Size of Structure s in bytes is 8
✌
✆
Here, sum of memory bytes calculated from structure members, is rounded off upward
so that it is perfect multiple of the largest data type member of that structure. This is
because, number of elements (n) in an array is given by
n =
Sum of Bytes
sizeof(data type)
Where n is an integer. If there are multiple datatypes as in the case of a structure, if bytes
are not multiple of all member datatypes’ size, then n becomes fraction. This rounding
off is done to make structure operation easy. Take another case:
✞
1 struct s {
int id1; //4 bytes for data
3 double id2; //8 bytes for data
};// total size will be equal to sum of all
5 // bytes , upward rounded off to , multiple
//to size of largest structure member.
✌
✆
✞
#include <stdio.h>
2
struct s {
4 int id1;
double id2;
6 }; // Total 12 bytes rounded up to
// 8*2=16 bytes is size of s
3.3. DATA STRUCTURES 401
8
int main () {
10 printf("Size of Structure s in bytes is ");
printf("%d.n", sizeof(struct s));
12 return 0;
}
✌
✆
✞
Size of Structure s in bytes is 16
✌
✆
✞
1 struct s {
int id1; //4 bytes for data
3 double *id2; //4 bytes for address
};// total size will be equal to sum of all
5 // bytes , upward rounded off to , multiple
//to size of largest structure member.
✌
✆
✞
#include <stdio.h>
2
struct s {
4 int id1;
double *id2;
6 }; // Total 8 bytes rounded up to
// 4*2=8 bytes is size of s
8
int main () {
10 printf("Size of Structure s in bytes is ");
printf("%d.n", sizeof(struct s));
12 return 0;
}
✌
✆
✞
Size of Structure s in bytes is 8
✌
✆
Next example
✞
1 struct s {
int id1; //4 bytes for data
3 char id2; //1 byte for data
};// total size will be equal to sum of all
5 // bytes , upward rounded off to , multiple
//to size of largest structure member.
✌
✆
✞
#include <stdio.h>
2
struct s {
4 int id1;
char id2;
6 }; // Total 5 bytes rounded up to
// 4*2=8 bytes is size of s
402 File & Data Structure
8
int main () {
10 printf("Size of Structure s in bytes is ");
printf("%d.n", sizeof(struct s));
12 return 0;
}
✌
✆
✞
Size of Structure s in bytes is 8
✌
✆
Next example
✞
1 struct s {
char id1; //1 byte for data
3 char id2; //1 byte for data
};// total size will be equal to sum of all
5 // bytes , upward rounded off to , multiple
//to size of largest structure member.
✌
✆
✞
#include <stdio.h>
2
struct s {
4 char id1;
char id2;
6 }; // Total 2 bytes rounded up to
// 1*2=2 bytes is size of s
8
int main () {
10 printf("Size of Structure s in bytes is ");
printf("%d.n", sizeof(struct s));
12 return 0;
}
✌
✆
✞
Size of Structure s in bytes is 2
✌
✆
Next example
✞
1 struct s {
char *id1; //4 bytes for address
3 char *id2; //4 bytes for address
};// total size will be equal to sum of all
5 // bytes , upward rounded off to , multiple
//to size of largest structure member.
✌
✆
✞
#include <stdio.h>
2
struct s {
4 char *id1;
char *id2;
6 }; // Total 8 bytes rounded up to
3.3. DATA STRUCTURES 403
// 4*2=8 bytes is size of s
8
int main () {
10 printf("Size of Structure s in bytes is ");
printf("%d.n", sizeof(struct s));
12 return 0;
}
✌
✆
✞
Size of Structure s in bytes is 8
✌
✆
Next example
✞
1 struct s {
char id1 [5]; //5 bytes for data
3 char id2; //1 byte for data
};// total size will be equal to sum of all
5 // bytes , upward rounded off to , multiple
//to size of largest structure member.
✌
✆
✞
#include <stdio.h>
2
struct s {
4 char id1 [5];
char id2;
6 }; // Total 6 bytes rounded up to
// 1*6=6 bytes is size of s
8
int main () {
10 printf("Size of Structure s in bytes is ");
printf("%d.n", sizeof(struct s));
12 return 0;
}
✌
✆
✞
Size of Structure s in bytes is 6
✌
✆
Next example
✞
1 struct s {
char id1 [5]; //5 bytes for data
3 char *id2; //4 bytes for address
};// total size will be equal to sum of all
5 // bytes , upward rounded off to , multiple
//to size of largest structure member.
✌
✆
✞
#include <stdio.h>
2
struct s {
4 char id1 [5];
char *id2;
404 File & Data Structure
6 }; // Total 9 bytes rounded up to
// 4*3=12 bytes is size of s
8
10 int main () {
printf("Size of Structure s in bytes is ");
12 printf("%d.n", sizeof(struct s));
return 0;
14 }
✌
✆
✞
Size of Structure s in bytes is 12
✌
✆
Next example
✞
1 struct s {
char id1 [5]; //5 bytes for data
3 double id2; //8 bytes for address
};// total size will be equal to sum of all
5 // bytes , upward rounded off to , multiple
//to size of largest structure member.
✌
✆
✞
#include <stdio.h>
2
struct s {
4 char id1 [5];
double id2;
6 }; // Total 13 bytes rounded up to
// 8*2=16 bytes is size of s
8
int main () {
10 printf("Size of Structure s in bytes is ");
printf("%d.n", sizeof(struct s));
12 return 0;
}
✌
✆
✞
Size of Structure s in bytes is 16
✌
✆
Next example
✞
1 struct s {
char id0 [10]; //10 bytes for data
3 char id1 [10]; //10 bytes for data
char id2 [11]; //11 bytes for data
5 int id3 [2]; //8 bytes for data
int id4 [5]; //20 bytes for data
7 double id5; //8 bytes for address
};// total size will be equal to sum of all
9 // bytes , upward rounded off to , multiple
//to size of largest structure member.
✌
✆
3.3. DATA STRUCTURES 405
✞
#include <stdio.h>
2
struct s {
4 char id0 [10];
char id1 [10];
6 char id2 [11];
int id3 [2];
8 int id4 [5];
double id5;
10 }; // Total 67 bytes rounded up to
// 8*9=72 bytes is size of s
12
int main () {
14 printf("Size of Structure s in bytes is ");
printf("%d.n", sizeof(struct s));
16 return 0;
}
✌
✆
✞
Size of Structure s in bytes is 72
✌
✆
Here is working example of struct function:
✞
1 #include <stdio.h>
3 struct student {
int id;
5 char *name ;
float perc ;
7 } st , st1 , st2;
9 int main () {
st.id = 1;
11 st1.name = "Arun Umrao";
st2.perc = 90.5;
13 printf("Id is: %d n", st.id);
printf("Name is: %s n", st1.name );
15 printf("Percentage is: %f n", st2.perc );
return 0;
17 }
✌
✆
✞
Id is: 1
Name is: Arun Umrao
Percentage is: 90.500000
✌
✆
Another simple example is given below.
✞
1 #include <stdio.h>
3 struct data {
406 File & Data Structure
int val;
5 float b;
};
7
int main (void ) {
9 struct data s;
s.val = 12;
11 s.b = 3.14159;
printf("The val field in s is: %dn", s.val);
13 return 0;
}
✌
✆
✞
The val field in s is: 12
✌
✆
Pointer can be also used in structure. An instance of a structure ‘data’ using a pointer is
declared as
✞
1 data *<variable >;
✌
✆
Member values of the structure declared with pointer are initialized or accessed by using
operator −> (indirect member access). See the following syntax, in which a structure
‘Func’ is declared by using a pointer and its member values are set by using operator −
>.
✞
1 struct Func {
int val;
3 float fl;
};
5 struct Func *b;
b->val = 3491;
✌
✆
st st++
val fl
A working example is
✞
#include <stdio.h>
2
struct Func {
4 int val;
float fl;
6 };
8 int main (void ) {
/* Func struct required for pointer */
10 struct Func a;
/* this is a pointer to a struct Func */
3.3. DATA STRUCTURES 407
12 struct Func *b;
b->val = 3491;
14 printf("The value of b is %d.", b->val);
return 0;
16 }
✌
✆
✞
The value of b is 3491.
✌
✆
A struct data can also be passed to a function by using address of procedure. See the
example below in which data struct is passed to function ‘Plantation’.
✞
1 #include <stdio.h>
3 /* Data structure */
struct Data {
5 int Trees;
int Plants;
7 };
9 /* function Plantation with data structure as pointer */
void Plantation (struct Data *f) {
11 f->Trees = 10;
f->Plants = 20;
13 }
15 int main (void ) {
/* Struct data structure */
17 struct Data Bio;
/* Pass address ‘Bio ’ into struct ‘Data ’ as pointer */
19 Plantation (& Bio);
printf("Trees : %dn", Bio.Trees); /* prints "10" */
21 printf("Plants : %dn", Bio.Plants); /* prints "20" */
return 0;
23 }
✌
✆
✞
Trees : 10
Plants : 20
✌
✆
A constant pointer, once holds an address cannot change to the new address. It means a
constant pointer, if already pointing to an address, cannot point to a new address.
✞
#include <stdio.h>
2
int main (void ) {
4 char ch = ’A’;
char cH = ’B’;
6
char * const ptr = &ch; // A constant pointer
8 ptr = &cH; // Illegal way of pointer .
408 File & Data Structure
10 return 0;
}
✌
✆
In case of pointer to structure, if the things on the left of the ‘.’ (dot) or ‘−>’ operator
is qualified (with const or volatile) then the result is also has those qualifiers associated
with it. In the following example, when the pointer points to a qualified type the result
got is also qualified.
✞
1 #include <stdio.h>
#include <stdlib.h>
3
struct myStruct {
5 int i;
};
7
main () {
9 /* Initialisation of structures . */
struct myStruct *Ptr , s_item;
11 /* Initialisation of structures of constant qualifier . */
const struct myStruct *s_Ptr;
13 /* Set the item value.*/
s_item.i = 1; /* OK */
15 /* Assigning new pointer .*/
Ptr = &s_item;
17 Ptr ->i += 2; /* OK */
/* Constant qualified pointer.*/
19 s_Ptr = &s_item;
s_Ptr ->i = 0; /* Not OK as points to constant type qualifier . */
21
exit ( EXIT_SUCCESS );
23 }
✌
✆
A structure can also be initialized at the starting of program if structure is defined as
✞
1 struct employee {
int no;
3 int sex;
int age;
5 };
struct employee EmpNo={<int >, <int >, <int >};
✌
✆
The following example clears the initialization of the structure.
✞
#include <stdio.h>
2
struct employee {
4 int no;
int sex;
6 int age;
};
8
3.3. DATA STRUCTURES 409
int main () {
10 /* Structure declared and initialized .*/
struct employee EmpNo ={10 ,1 ,15};
12 printf("%dt%dt%dn", EmpNo.no , EmpNo.sex , EmpNo.age);
return 0;
14 }
✌
✆
A self referential structures has same member name as its name is. See the following
example.
✞
struct myStruct {
2 int i;
char j[10];
4 struct myStruct *myStructRef ;// Legal
};
✌
✆
In case of pointer type self referral, size of a pointer to a structure is known to compiler
even before the size of the structure has been determined. Note that the self referential
structure should be a pointer not a structure. For example, at above structure, ‘myS-
tructRef’ is pointer not a structure itself. If it is a structure, then it will contain member
‘myStructRef’ recursively (member within member).
✞
1 struct myStruct {
int i;
3 char j[10];
struct myStruct myStructRef ; // Illegal
5 };
✌
✆
Following type of self referral is also illegal.
✞
1 typedef struct {
int i;
3 char j[10];
myStructAlias *myStructRef ; // Illegal
5 } myStructAlias ;
✌
✆
The reason is that the type name is defined after the declaration of structure, therefore,
line
✞
1 struct myStruct *myStructRef ; // Illegal
✌
✆
will show error as self referral structure is declared before the type name is defined. The
legal form is given below:
✞
1 typedef struct myStruct {
int i;
3 char j[10];
struct myStruct *myStructRef ; // Legal
5 } myStructAlias ;
✌
✆
410 File & Data Structure
Nested Structure
Structure within structure i.e. nested structure can also be declared by using either normal
variable or pointer. In following example, a nested structure is declared and declared by
simple variable. From structural inheritance, inner structure is accessible from instances
of outer structure.
✞
1 #include <stdio.h>
3 int main () {
5 /* date structure */
struct date {
7 int day;
int month;
9 int year ;
};
11
/* variety structure */
13 struct variety {/* Upper level structure */
char *name ;
15
/* Date is Lower level nested structure . it is *
17 * declared as normal structure . Elements of *
* date structure are accessed by dot (.). */
19 struct date date ;
} tr; /* Structure declared as normal variable . *
21 * Elements can be accessed by (.) symbol.*/
23 /* Accessing structure elements by using synopsis like
* up_level_struct (.) up_level_elem
25 * or
* up_level_struct (.) low_level_struct (.) low_level_elem */
27 tr.name = "A";
tr.date .day = 10;
29 printf("Name : %sn", tr.name );
printf("day : %dn", tr.date .day);
31 return 0;
}
✌
✆
✞
Name : A
day : 10
✌
✆
In simple variable type declaration of structure, elements are accesses by using dot (.).
Using of pointer symbol (−>) throws the errors.
✞
#include <stdio.h>
2
int main () {
4
/* date structure */
3.3. DATA STRUCTURES 411
6 struct date {
int day;
8 int month;
int year ;
10 };
12 /* variety structure */
struct variety {/* Upper level structure */
14 char *name ;
16 /* Date is Lower level nested structure . it is *
* declared as normal structure . Elements of *
18 * date structure are accessed by dot (.). */
struct date date ;
20 } tr; /* Structure declared as normal variable . *
* Elements can be accessed by (.) symbol.*/
22
/* Accessing structure elements by using synopsis like
24 * up_level_struct (.) up_level_elem
* or
26 * up_level_struct (.) low_level_struct (.) low_level_elem */
tr.name = "A";
28 tr.date .day = 10;
30 /* Following line show errors. Reason is that we are trying*
*to access the element by pointer symbol (->) even though*
32 *the structure ‘tr ’ is declared here as normal variable . */
tr ->date .month = 11;
34 printf("Name : %sn", tr.name );
printf("day : %dn", tr.date .day);
36 return 0;
}
✌
✆
Other-way to assign a structure inside another struct is pointer method. In pointer
method, elements are accessed by using pointer symbol (−>) and dot (.).
✞
1 #include <stdio.h>
3 int main () {
5 /* date structure */
struct date {
7 int day;
int month;
9 int year ;
};
11
/* variety structure */
13 struct variety {/* Upper level structure */
char *name ;
15
412 File & Data Structure
/* Date is Lower level nested structure . it is *
17 * declared as normal structure . Elements of *
* date structure are accessed by dot (.). */
19 struct date date ;
} *tr; /* Structure declared as pointer variable . *
21 * Elements can be accessed by (->) symbol.*/
23 /* Accessing structure elements by using synopsis like
* up_level_struct (->) up_level_elem
25 * or
* up_level_struct (->) low_level_struct (.) low_level_elem */
27 tr ->name = "A";
tr ->date .day = 10;
29 printf("Name : %sn", tr ->name );
printf("day : %dn", tr ->date .day);
31 return 0;
}
✌
✆
✞
Name : A
day : 10
✌
✆
Again, indirect membership operator or structure pointer operator (−>) is not used in
the level or element of the structure declared as normal variable.
✞
#include <stdio.h>
2
int main () {
4
/* date structure */
6 struct date {
int day;
8 int month;
int year ;
10 };
12 /* variety structure */
struct variety {/* upper level structure */
14 char *name ;
16 /* Date is Lower level nested structure . it is *
* declared as normal structure . Elements of *
18 * date structure are accessed by dot (.). */
struct date date ;
20 } *tr; /* Structure declared as pointer variable .*
* Elements are accessed by (->) symbol. */
22
/* Following lines show errors. We are trying *
24 *to access the elements of structure ‘date ’ *
*by pointer symbol (->) while the structure *
26 *‘date ’ is declared here as normal variable .*/
tr ->date ->day = 10;
3.3. DATA STRUCTURES 413
28 tr.date ->day = 10;
return 0;
30 }
✌
✆
But the lower level elements can also be accessed by using pointer symbol (−>) if lower
level structure is also declared as pointer level.
✞
#include <stdio.h>
2
int main () {
4
/* date structure */
6 struct date {
int day;
8 int month;
int year ;
10 };
12 /* variety structure */
struct variety {/* upper level structure */
14 char *name ;
/* Date is Lower level nested structure . it is *
16 * declared as pointer structure . Elements of *
* date structure are accessed by dot (->). */
18 struct date *date ;
} *tr; /* Structure declared as pointer variable . *
20 * Elements can be accessed by (->) symbol.*/
22 /* Accessing structure elements by using synopsis like
* up_level_struct (->) up_level_elem
24 * or
* up_level_struct (->) low_level_struct (->) low_level_elem */
26 tr ->date ->day = 10;
tr ->date ->month = 10;
28 printf("Day : %dn", tr ->date ->day);
printf("Month : %dn", tr ->date -> month);
30 return 0;
}
✌
✆
✞
Day : 10
Month : 10
✌
✆
In above examples, it is clarified that, elements of structures declared as variable type are
accessed by using dot (.) and elements of structure declared as pointer type are accessed
by using indirect membership operator or structure pointer operator (−>).
✞
#include <stdio.h>
2
int main () {
4
414 File & Data Structure
/* date structure */
6 struct date {
int day;
8 int month;
int year ;
10 };
12 /* variety structure */
struct variety {/* up_level_struct (uls)*/
14 char *name ;
16 /* Date is Lower level nested structure . it is *
* declared as pointer structure . Elements of *
18 * date structure are accessed by dot (->). */
struct date *date ;
20 } tr; /* Structure declared as normal variable .*
* Elements can be accessed by dot (.). */
22
/* Accessing structure elements by using synopsis like
24 * up_level_struct (.) up_level_elem
* or
26 * up_level_struct (.) low_level_struct (->) low_level_elem */
tr.date ->day = 10;
28 tr.date ->month = 10;
printf("Day : %dn", tr.date ->day);
30 printf("Month : %dn", tr.date -> month);
return 0;
32 }
✌
✆
✞
Day : 10
Month : 10
✌
✆
Structure As Arguments
Like other variables, file pointers and function pointers, a structure can also be passed
to a function as its argument. The method of passing a structure to a function is given
below:
✞
int myFunc(struct <structure name > <local var >);
✌
✆
In the following example, structure ‘g len’ is passed to function ‘sum’. Numerical values
of structure elements are get summed and returned to the caller. shown in the example
below:
✞
1 #include <stdio.h>
#define TREE_NUM 50
3
/* Structure for garden tree length.*/
5 struct g_len {
3.3. DATA STRUCTURES 415
char gardens[TREE_NUM ];
7 double t_len_1;
double t_len_2;
9 };
11 /* Structure passed to the function .*/
double sum(struct g_len val) {
13 return (val.t_len_1 + val.t_len_2 );
}
15
int main (void ) {
17 /* Initialized the structure .*/
struct g_len sbi = {
19 "G DELHI",
6524.12 ,
21 9458.87
};
23 printf("Tree length is %.2fm.n", sum(sbi));
return 0;
25 }
✌
✆
✞
Tree length is 15982.99 m.
✌
✆
Structure data allows us to write data of desired size into text or binary file. To write
struct data into a file we use fwrite function as
✞
1 FILE *fp; /*A file stream */
struct TreeData { /* Structure TreeData */
3 int x;
int y;
5 }
/* Create TreeData space.*/
7 struct TreeData *td = malloc(sizeof ( struct TreeData ));
/* Write structure data into file .*/
9 fwrite(td , sizeof (struct TreeData ), 1, fp);
✌
✆
Here is complete example:
✞
1 #include <stdio.h>
3 struct TreeData {
int x_old;
5 int y_old;
int x_new;
7 int y_new;
int val;
9 };
11 void insert(char *f, int x_old , int y_old , int val) {
struct TreeData *td = malloc(sizeof (struct TreeData ));
13 FILE *fp;
416 File & Data Structure
int xnew ;
15 int ynew ;
if (td ->x_new == 0 || td ->y_new == 0) {
17 td ->x_new = 0;
td ->y_new = 0;
19 } else {
xnew = td ->x_new;
21 ynew = td ->y_new;
}
23 td ->x_old = x_old;
td ->y_old = y_old;
25 td ->val = val;
fp = fopen(f, "wb");
27 fwrite(td , sizeof ( struct TreeData ), 1, fp);
fclose(fp);
29 td ->x_new = xnew + 1;
td ->y_new = ynew + 1;
31 }
33 int main () {
char *f = "TreeNode .txt";
35 struct TreeData myNode;
insert(f, 0, 0, 95);
37 return 0;
}
✌
✆
Multi-Dimensional Struct
Technically a multidimensional structure can not be declared. But tricking methods
can be used to store a multidimensional data with help of structure. For example, a
two dimensional values can be stored via structure if we declared a structure with two
elements. One for storing data of one dimension and other for storing data of second
dimension. Yet a structure can be declared as an array. A structure capable of storing
two dimensional data is declared as given below:
✞
struct myStruct { /* Structure with 2 elements */
2 int i; /* First element of 4 bytes size */
int j; /* Second element of 4 bytes size */
4 };
struct myStruct s[2]; /* Initialize 2-dim structure for *
6 *storing two elements of an array*/
✌
✆
The memory size required to store this structure is equal to the product of number of
dimension of structure and total size of structure elements. In above syntax, size of
structure is (4 + 4) × 2 = 16 bytes. See the example below:
✞
#include <stdio.h>
2
int main () {
4
3.3. DATA STRUCTURES 417
struct twoDimStruct {
6 int x;
int y;
8 };
struct twoDimStruct s[10];
10 printf("Size of Structure is %d bytes.n", sizeof (s));
return 0;
12 }
✌
✆
✞
Size of Structure is 80 bytes.
✌
✆
Here, structure creates space for data storage, hence memory allocation is not required.
But we can use dynamically allocated memory as shown below:
✞
1 #include <stdio.h>
3 int main () {
int i;
5
typedef struct {
7 int x;
int y;
9 } mStruc;
/* Allocate memory space for all *
11 *columns of size (4+4) *10 bytes.*/
mStruc **s = (mStruc **) malloc (10 * sizeof (mStruc *));
13 for (i = 0; i < 10; i++) {
/* Allocate memory space for each *
15 *rows as group of above columns .*/
s[i] = (mStruc *) malloc (10 * sizeof (mStruc));
17 }
return 0;
19 }
✌
✆
Assume a four element structure as syntaxed below:
✞
1 typedef struct {
int x; /*4 bytes long */
3 char c; /*1 byte long */
int y; /*4 bytes long */
5 char k; /*1 byte long */
} e;
7 /* **s points to memory for 10 elements *
* where each element is 10 bytes long .*
9 * it forms columns of the each row. */
e **s = (e **) malloc (10 * sizeof (e *));
11 for (i = 0; i < 10; i++) {
/* Allocate memory space for each *
13 *rows as group of above columns .*/
s[i] = (e *) malloc (10 * sizeof (e));
15 }
✌
✆
418 File & Data Structure
The memory space is created for a structure array of 10 × 10. The memory space is
reserved with help of malloc command. The memory space is represented by:
n n n n
x
c
c
n n n n
y
c
k
e[0]
∗∗
s
n n n n
x
c
c
n n n n
y
c
k
e[1]
s[0]
We can store value for each structure and retrieve it as and when required. See the
example below:
✞
1 #include <stdio.h>
3 int main () {
5 struct twoDimStruct {
int x;
7 int y;
};
9 struct twoDimStruct s[10];
s[1]. x = 5;
11 s[1]. y = 10;
s[3]. y = 25;
13 printf("s[1]. x = %d.n", s[1]. x);
printf("s[1]. y = %d.n", s[1]. y);
15 printf("s[3]. x = %d.n", s[3]. x);
printf("s[3]. y = %d.n", s[3]. y);
17 return 0;
}
✌
✆
✞
s[1]. x = 5.
s[1]. y = 10.
s[3]. x = 1.
s[3]. y = 25.
✌
✆
When structure is declared as array, if reserves memory equal to the product of size of
structure and structure array size. For example, the statement
✞
struct twoDimStruct s[10];
✌
✆
memory space for ten struct elements are reserved. Total size of instance ‘s’ is (4+4)×10 =
80 bytes. If structure is declared as
✞
1 struct twoDimStruct s[10][3];
✌
✆
then it has ten rows and three columns in which each element has structure elements ‘x’
and ‘y’. See the example given below:
3.3. DATA STRUCTURES 419
✞
1 #include <stdio.h>
3 int main () {
5 struct twoDimStruct {
int x;
7 int y;
};
9 struct twoDimStruct s[4][3];
s[1][0]. x = 5;
11 s[1][0]. y = 6;
s[1][1]. x = 7;
13 s[1][1]. y = 8;
s[1][2]. x = 9;
15 s[1][2]. y = 10;
printf("%dt%dt", s[1][0].x, s[1][0]. y);
17 printf("%dt%dt", s[1][1].x, s[1][1]. y);
printf("%dt%dn", s[1][2].x, s[1][2]. y);
19 return 0;
}
✌
✆
✞
5 6 7 8 9 10
✌
✆
The memory arrangement of the two dimensional structure is shown in the following
figure.
x00 x01 x02
y00 y01 y02
x10 x11 x12
y10 y11 y12
x20 x21 x22
y20 y21 y22
x30 x31 x32
y30 y31 y32
The address of the structure elements are retrieved in the following example to check
the order of elements in the memory.
✞
1 #include <stdio.h>
3 int main () {
5 struct twoDimStruct {
int x;
7 int y;
};
9 struct twoDimStruct s[4][3];
s[1][0]. x = 5;
11 s[1][0]. y = 6;
s[1][1]. x = 7;
420 File & Data Structure
13 s[1][1]. y = 8;
s[1][2]. x = 9;
15 s[1][2]. y = 10;
printf("%xt%xn", &(s[1][0].x), &(s[1][0].y));
17 printf("%xt%xn", &(s[1][1].x), &(s[1][1].y));
printf("%xt%xn", &(s[1][2].x), &(s[1][2].y));
19 return 0;
}
✌
✆
✞
c280b9b8 c280b9bc
c280b9c0 c280b9c4
c280b9c8 c280b9cc
✌
✆
A structure can be returned from a function but an array can not be so. See the following
example, in which a copy of the local, automatically allocated structure is made on return
and then the local copy is destroyed.
✞
1 #include <stdio.h>
3 typedef struct {
double square , cube ;
5 } A;
7 A getAns( double in) {
A out = {
9 . square = in*in ,
.cube = in * in * in
11 };
return out;
13 }
15 int main () {
A res = getAns (3);
17 printf("Result: %gt%gtn", res.square , res.cube );
return 0;
19 }
✌
✆
✞
Result: 9 27
✌
✆
Return Structure from Function
We may return structure from inside of a function. Note that the address of returned
structure is address of first member of the structure. Value of first member of structure is
printed in output console with warning. If there are multiple members in a structure then
it is good practice to call member of the structure rather than calling whole structure.
See the example below:
✞
1 #include <stdio.h>
3.3. DATA STRUCTURES 421
3 struct st {
int i; /* First element */
5 int j; /* Second element */
};
7
struct st myF(int x) {
9 struct st s; /* Create structure object*/
s.i = x; /* Set value to first element */
11 s.j = 2 * x; /* Set value to second element */
return s; /* Return structure address */
13 }
15 int main () {
17 /* Prints first element of the structure */
printf("%dn",myF (20) .i);
19 /* Prints second element of the structure */
printf("%dn",myF (20) .j);
21 return 0;
}
✌
✆
✞
20
40
✌
✆
3.3.2 Enumerate
In C, enumerations are created by explicit definitions, which use the enum keyword and
are reminiscent of struct and union definitions. See example below.
✞
#include <stdio.h>
2
enum {
4 /*0*/ /*1*/ /*2*/
TRUE , FALSE , NO
6 } b = NO;
8 int main (int argc , char ** argv ) {
printf("bool : %dn", b);
10
return 0;
12 }
✌
✆
✞
bool : 2
✌
✆
C also allows the programmer to choose the values of the enumeration constants explicitly,
even without type.
422 File & Data Structure
✞
1 #include <stdio.h>
3 enum {
TRUE = 0, FALSE = 1, NO = 10
5 } b = NO;
7 int main (int argc , char ** argv ) {
printf("bool : %dn", b);
9
return 0;
11 }
✌
✆
✞
bool : 10
✌
✆
In enumerate the values are assigned successively. If any enum key is set to a specific
value then next enum key has value one larger than its preceding enum key.
✞
1 #include <stdio.h>
3 int main () {
5 enum COLORS {
BLUE , /* Index value 0*/
7 GREEN = 3, /* Index value 3*/
YELLOW , /* Index value 4*/
9 RED = 2, /* Index value 2*/
BLACK /* Index value 3*/
11 };
printf("The colors are:n");
13 printf("%dn", BLUE );/*0*/
printf("%dn", YELLOW);/*4*/
15 printf("%dn", BLACK);/*3*/
return 0;
17 }
✌
✆
✞
The colors are:
0
4
3
✌
✆
3.3.3 Unions
The definition of a union is similar to that of a struct. The difference between the two
is that in a struct, the members occupy different areas of memory, but in a union, the
members occupy the same area of memory. Thus, in the following type, for example:
✞
union {
2 char c;
3.3. DATA STRUCTURES 423
int d;
4 } u;
✌
✆
The programmer can access either ‘u.c’ or ‘u.d’, but not both at the same time. In the
following example, we modify only value of member ‘c’ and access it, we get the correct
result.
✞
#include <stdio.h>
2 #include <string.h>
4 union Data {
char c;
6 int d;
};
8
int main () {
10 union Data data ;
12 data .c = 10;
14 printf("data .c : %dn", data .c);
16 return 0;
}
✌
✆
✞
data .c : 10
✌
✆
data.c
0000 1010
In the following example, we modify values of members ‘c’ and ‘d’ and access it, we get the
incorrect result as ‘data.c’ and ‘data.d’ uses same memory space and ‘data.d’ overwrite
and modified the value of ‘data.c’ as well. Thus we get undesirable value of ‘data.c’ but
correct value of ‘data.d’.
✞
1 #include <stdio.h>
#include <string.h>
3
union Data {
5 char c;
int d;
7 };
9 int main () {
union Data data ;
11
424 File & Data Structure
data .c = ’C’;
13
data .d = 201170739;
15 /*|<--------------data .d--------------->|*
* 00001011 11111101 10011111 00110011 *
17 * |<-data .c->|*/
19 printf("data .c : %cn", data .c);
printf("data .d : %dn", data .d);
21
return 0;
23 }
✌
✆
✞
data .c : 3
data .d : 201170739
✌
✆
data.d
data.c
0000 1011 1111 1101 1001 1111 0011 0011
Since ‘data.c’ and ‘data.d’ occupy the same area of memory, so, modifying the value of one
member of union modifies the values of the other members, sometimes in unpredictable
ways. The size of a union is the size of its largest member. Another simple example is
given again.
✞
#include <stdio.h>
2 #include <string.h>
4 union Data {
char c;
6 int d;
char str [15];
8 };
10 int main () {
union Data data ;
12 /* update shared memory as char */
data .c = ’C’;
14 /* update shared memory as integer */
data .d = 201170739;
16 /* update shared memory as string */
strcpy(data .str , "C Programming ");
18
/* Read last updates as character */
3.3. DATA STRUCTURES 425
20 printf("data .c : %cn", data .c);
/* Read last updates as integer */
22 printf("data .d : %dn", data .d);
/* Read last updates as string*/
24 printf("data .str : %sn", data .str);
26 return 0;
}
✌
✆
✞
data .c : C
data .d : 1917853763
data .str : C Programming
✌
✆
union is used as shared structure in which shared memory is updated or accessed for
last value of any data type. Each element of the union structure reads/updates shared
memory bytes in same data type as it is declared in the union.
3.3.4 Stack
A stack is a particular kind of abstract data type or collection in which the principal (or
only) operations on the collection are the addition of an entity to the collection, known
as “push” and removal of an entity, known as “pop”. The relation between the push and
pop operations is such that the stack is a Last-In-First-Out (LIFO) data structure. In
most high level languages, a stack can be easily implemented either through an array or a
linked list. A stack needs to elements, one stack counter and second stack memory. Stack
memory either holds memory address of data located at the address (i.e. string stack) or
holds actual numeric values (integer stack). Stack pointer/counter controls to how many
elements may be pushed into a stack. It prevents pushing of an element in the memory
location that is not part of the stack. For example see following code which has declared
an array of 4 integers (i.e. stack size is four) and memory is allocated to store these 4
integer values.
✞
1 int *myA;
myA = malloc (4*4);
✌
✆
Here, 16 bytes are reserved to hold 4 integer values. If we try to add 5th
element into
this array, the array parameter reached beyond the allocated memory. It is violation of
shared memory. Stack will graphically represent as given below:
myA
Stack (0 to 3)
Low count High count
Here, pointer ‘myA’ should never be pushed beyond the range of 16 bytes. Initially,
‘myA’ is at the root of the stack, i.e. at the index 0. Now, push an integer into the stack.
426 File & Data Structure
✞
*myA =10;
✌
✆
Integer 10 is stored in the current memory location of ‘myA’. It is caller’s responsibility
to increase the pointer otherwise the next push shall put the new value in same location
and old value shall be overwritten by new value. The pointer location is incremented one
by
✞
1 myA ++;
✌
✆
Now, stack shall be looked like
10
myA
Stack (0 to 3)
Low count High count
By incrementing/decrementing the pointer within the memory allocated range, we
can either push a value into the stack or may popped a value from the stack. A sudden
jump of pointer within memory location is also permitted.
✞
1 myA +3;
*myA =50;
✌
✆
Now, stack shall be looked like
10 50
myA
Stack (0 to 3)
Low count High count
Note that, one integer is four bytes long, therefore, ‘myA+3’ shall make a jump of 12
bytes to the pointer ‘myA’. Stack may be declared as pointer or as an array.
✞
int myA [4]; /* Declaration & memory allocation */
2 /* Other method */
int *myA; /* Declaration */
4 myA = malloc (4*4); /* Memory allocation */
✌
✆
Location of stack elements may be accessed by indexing or by dereferencing the array. If
stack is considered as a pointer then it is accessed as explained above. If it is considered
as an array then stack shall be looked like as given below and its elements can be accessed
by indexing them.
3.3. DATA STRUCTURES 427
myA[0] myA[1] myA[2] myA[3]
Stack (0 to 3)
Low count High count
In computer, index counting starts from 0 to infinity.
Push A Value
Pushing a value to a stack means adding an element into the stack. A value is pushed
at the current location of the pointer of stack counter (in case of array). Counter, some
time is used as index value. For example, in array type stack, 2nd
element is pushed at
index 1 of ‘myA’.
✞
myA [1] = 20;
✌
✆
20
myA[1]
Stack (0 to 3)
Low count High count
If counter or index of array is incremented by more than one, then it is also called pushing
of element as the location of stack pointer is changed and new element shall be pushed
here.
20
myA[3]
Stack (0 to 3)
Low count High count
Pop A Value
Normally, system retrieves value from the current location of pointer or index counter.
Therefore, popping does not mean that value at particular location is chagned to null
before the changing the location of pointer or counter. If counter/index/pointer is decre-
mented by two without retrieving the values, then it is also said popping of elements even
though the values are intact at their memory locations.
10 20 30 40
myA[3]
Stack (0 to 3)
Low count High count
428 File & Data Structure
Assume that, initially pointer is at location ‘myA[3]’ and it is decremented by two
locations, then we say that 3rd
and 4th
elements are popped.
10 20 30 40
myA[1]
Stack (0 to 3)
Low count High count
Now, the pointer/counter is pointing to 2nd
element of the stack. Adding of new
element will change the value at this memory location and retrieval may allow utilization
of the value stored at this location. Actually, it is user’s responsibility to control the
position of pointer or index within the stack.
Array in Stack
The array implementation aims to create an array where the first element (usually at the
zero-offset) is at the bottom. I.e., array[0] is the first element pushed onto the stack and
the last element popped off. The program must keep track of the size or the length of
the stack.
✞
1 data type struct {
size_t size ; // element counter
3 int items[STACKSIZE ]; // stack memory
} STACK;
✌
✆
The push() operation is used both to initialize the stack, and to store values into it. It
is responsible for inserting (copying) the value in array and for incremental the element
counter. Note that, when an element is pushed into the stack, counter should be increased
by one and when one element is removed from the stack, counter should be decreased by
one. It is also need to check that the array is not completely full or completely empty.
✞
void push (STACK *ps , int x) {
2 if (ps ->size == STACKSIZE ) {
fputs("Error: stack overflow n", stderr);
4 abort();
} else
6 ps ->items[ps ->size ++] = x;
}
✌
✆
The pop() operation is responsible for removing a value from the stack, and decremented
the value of array. It is also need to check that the array is not already empty. Popping
of an element from the stack, decreases the counter by one.
✞
1 int pop(STACK *ps) {
if (ps ->size == 0) {
3 fputs("Error: stack underflow n", stderr);
abort();
5 } else
3.3. DATA STRUCTURES 429
return ps ->items[--ps ->size ];
7 }
✌
✆
Following is the simple example that explains the stack in array by using struct structure
method.
✞
1 #include <stdio.h>
3 #define MAXSIZE 5
5 struct stack /* Structure definition for stack */ {
int stk[MAXSIZE ];
7 int top;
};
9
struct stack s;
11
/* Function declaration /Prototype */
13
void push (void );
15 int pop(void );
void display (void );
17
void main () {
19 int choice;
int option = 1;
21
s.top = -1;
23
printf("STACK OPERATION n");
25 while (option) {
printf(" --------------------n");
27 printf(" 1 --> PUSH n");
printf(" 2 --> POP n");
29 printf(" 3 --> DISPLAY n");
printf(" 4 --> EXIT n");
31 printf(" --------------------n");
33 printf("Enter your choice : n");
scanf("%d", &choice);
35
switch (choice) {
37 case 1:
push ();
39 break;
case 2:
41 pop();
break;
43 case 3:
display ();
45 break;
430 File & Data Structure
case 4:
47 return;
}
49
fflush(stdin);
51 printf("Do you want to continue (Type 0 or 1)?n");
scanf("%d", &option);
53 }
}
55
/* Function to add an element to the stack*/
57 void push () {
int num;
59 if (s.top == (MAXSIZE - 1)) {
printf("Stack is Full n");
61 return;
} else {
63 printf("Enter a valuen");
scanf("%d", &num);
65 s.top = s.top + 1;
s.stk[s.top] = num;
67 }
return;
69 }
71 /* Function to delete an element from the stack*/
int pop() {
73 int num;
if (s.top == -1) {
75 printf("Stack is Emptyn");
return (s.top);
77 } else {
num = s.stk[s.top ];
79 printf("poped element is = %dn", s.stk[s.top]);
s.top = s.top - 1;
81 }
return (num);
83 }
85 /* Function to display the status of the stack*/
void display () {
87 int i;
if (s.top == -1) {
89 printf("Stack is emptyn");
return;
91 } else {
printf("nThe status of the stack isn");
93 for (i = s.top; i >= 0; i--) {
printf("%dn", s.stk[i]);
95 }
}
3.3. DATA STRUCTURES 431
97 printf("n");
}
✌
✆
First screen of the program output is
✞
--------------------
1 --> PUSH
2 --> POP
3 --> DISPLAY
4 --> EXIT
--------------------
Enter your choice :
✌
✆
String in Stack
String can be stored as stack. To store string in stack, a stack variable of character type
is initialized. Generally, this stack variable is a two dimensional array, in which first
dimension represents the row number and second dimension represents to string size. For
example, a string stack of size 10, having largest string size of 20 characters is declared
as
✞
1 char myStack [10][20];
✌
✆
Here, stack size is 10 and we can put the string of length upto 20 characters.
3.3.5 Classes
In C, we can not declared function element inside the structure. This is why, it is hard
to call a function as object. Object oriented programming in C is restricted within scope
of the structure. There are four steps to be followed to create a function as object. The
steps involved, (i) create a class, (ii) deleted a class, (iii) update the class and (iv) access
the class.
Create Class
Here, using struct keyword, a class ‘myClass’ is declared. It has an element ‘variable’ of
int data type. The class is initialized to set the value of the class element ‘variable’ to 0.
✞
1 typedef struct myClass {
int variable ;
3 } *MyClass ;
5 MyClass myNewClass () {
MyClass this = malloc(sizeof *this );
7 this -> variable = 0;
return this ;
9 }
✌
✆
432 File & Data Structure
Delete Class
As each class when declared and called, a memory space is reserved to store data in
‘variable’. After execution of object function, the memory allocated, must be freed by
using free() function.
✞
1 void myNewClassDelete (MyClass * this ) {
if (this ) {
3 free (* this );
*this = NULL ;
5 }
}
✌
✆
Update Class
This function class updates the data of ‘variable’ according to the rules set by statements
and expressions inside this function.
✞
void myNewClassSet (MyClass this ) {
2 this -> variable = 1;
}
✌
✆
Access Class
It is main part of the program, from where we can access the object function. Result is
printed in output console by printf function.
✞
1 int main () {
MyClass obj = myNewClass ();
3 myNewClassSet (obj);
printf("%d", obj ->variable );
5 myNewClassDelete (& obj);
return 0;
7 }
✌
✆
Complete example using above four steps is given below:
✞
1 #include <stdlib.h>
#include <stdio.h>
3
typedef struct myClass {
5 int variable ;
} *MyClass ;
7
MyClass myNewClass () {
9 MyClass this = malloc(sizeof *this );
this -> variable = 0;
11 return this ;
}
13
3.3. DATA STRUCTURES 433
void myNewClassDelete (MyClass * this ) {
15 if (this ) {
free (* this );
17 *this = NULL ;
}
19 }
21 void myNewClassSet (MyClass this ) {
this -> variable = 1;
23 }
25 int main () {
MyClass obj = myNewClass ();
27 myNewClassSet (obj);
printf("%d", obj ->variable );
29 myNewClassDelete (& obj);
return 0;
31 }
✌
✆
3.3.6 Link List
Linked List (Array)
Arrays and linked list are linear data structure. In array, elements are stored in sequential
memory locations, while in linked list, elements are linked using pointers. Linked lists
are preferred over arrays as array has fixed size and insertion of element in between the
array elements is expensive.
11
0×042a
0×1225 34
0×1225
0×a22c 56
0×a22c
0×a2cc
myP
NULL
Linked lists have some drawbacks too. (i) Random access is not allowed. and (ii)
extra memory space for a nextPtr is required with each element of the list. A linked list
node is created as given below:
✞
1 struct list_Elem {
int data ;
3 struct list_Elem *nextElemPtr ;
};
✌
✆
In this prototype, element of structure is structure itself. It is forbidden in the structure
definition. But in fact it only contains a nextPtr to itself. It is allowed as by the time
the compiler reaches the nextPtr declaration it already knows that there is such a thing
as a ‘struct list Elem’ so the declaration is permitted. In fact, it is possible to make a
incomplete declaration of a structure by saying
434 File & Data Structure
✞
struct list_Elem ;
✌
✆
at some point before the full declaration. This will allow the declaration of pointers before
the full declaration is seen. It is also important in the case of cross-referencing structures
where each must contain a nextPtr to the other, as shown in the following example.
✞
1 struct s_1; /* Incomplete type */
3 struct s_2 {
int something ;
5 struct s_1 *sp;
};
7
struct s_1 { /* Full declaration */
9 float something ;
struct s_2 *sp;
11 };
✌
✆
This illustrates the need for incomplete types. It also illustrates an important thing about
the names of structure members: they inhabit a name-space per structure, so element
names can be the same in different structures without causing any problems. Incomplete
types may only be used where the size of the structure isn’t needed yet. A full declaration
must have been given by the time that the size is used. The later full declaration mustn’t
be in an inner block because then it becomes a new declaration of a different structure.
✞
1 struct x; /* Incomplete type */
3 /* valid uses of the tag */
struct x *p, func (void );
5
void f1(void ) {
7 struct x {
int i;
9 }; /* redeclaration ! */
}
11
/* full declaration now */
13 struct x {
float f;
15 } s_x;
17 void f2(void ) {
/* valid statements */
19 p = &s_x;
*p = func ();
21 s_x = func ();
}
23
struct x func (void ) {
25 struct x tmp;
3.3. DATA STRUCTURES 435
tmp.f = 0;
27 return (tmp);
}
✌
✆
The other principal way to get incomplete types is to declare arrays without specifying
their size, their type is incomplete until a later declaration provides the missing informa-
tion:
✞
int ar[ ]; /* incomplete type */
2 int ar [5]; /* complete type */
✌
✆
If you try that out, it will only work if the declarations are outside any blocks (external
declarations), but that’s for other reasons. There were three elements linked into the list,
which could have been built like this:
✞
struct list_Elem {
2 int data ;
struct list_Elem *nextPtr ;
4 } ar [3];
6 main () {
ar [0]. data = 5; /* Add data to first element */
8 ar [0]. nextPtr = &ar [1]; /* Add address of second element */
ar [1]. data = 99; /* Add data to second element */
10 ar [1]. nextPtr = &ar [2]; /* Add address of third element */
ar [2]. data = -7; /* Add data to third element */
12 ar [2]. nextPtr = 0; /* mark end of list */
return (0);
14 }
✌
✆
and the contents of the list can be printed in two ways. The array can be traversed in
order of index, or the pointers can be used as shown in the following example.
✞
#include <stdio.h>
2 #include <stdlib.h>
4 struct list_Elem {
int data ;
6 struct list_Elem *nextPtr ;
} ar [3];
8
main () {
10
struct list_Elem *lp;
12
ar [0]. data = 5; /* Add data to first element */
14 ar [0]. nextPtr = &ar [1]; /* Add address of second element */
ar [1]. data = 99; /* Add data to second element */
16 ar [1]. nextPtr = &ar [2]; /* Add address of third element */
ar [2]. data = -7; /* Add data to third element */
18 ar [2]. nextPtr = 0; /* mark end of list */
436 File & Data Structure
20 /* follow pointers */
lp = ar;
22 while (lp) {
printf("contents %dn", lp ->data );
24 lp = lp ->nextPtr ;
}
26 exit ( EXIT_SUCCESS );
}
✌
✆
✞
contents 5
contents 99
contents -7
✌
✆
Linked List (Pointer)
A node in a list is memory location from where new data is stored. In C, a node is created
like
✞
1 struct myNode {
int data ;
3 struct myNode *nextPtr ;
};
✌
✆
Above structure has two elements, one for storing data and other for storing the address
of next element. Hence, each structure of a linked list is group of two contents, ‘data’
and ‘address of next data location’.
✞
#include <stdio.h>
2 #include <stdlib.h>
4 struct myNode {
int data ;
6 struct myNode *nextPtr ;
};
8
void Push (struct myNode ** myP , int value) {
10 struct myNode* cNode = 
(struct myNode*) 
12 malloc(sizeof (struct myNode));
cNode ->data = value;
14 cNode ->nextPtr = (* myP);
(* myP) = cNode;
16 printf("Value is %d at address %xn",cNode ->data , &cNode ->data );
printf("Address of next value %d is : %xn" ,(cNode ->data +1) ,
cNode ->nextPtr);
18 }
20 int main () {
3.3. DATA STRUCTURES 437
struct myNode* head = NULL ;
22 int i=5;
while(i>0){
24 Push (&head , i);
i--;
26 }
return 0;
28 }
✌
✆
✞
urrent value is 5 at address of 215b010 --<--+
Address of next value 6 is : 0 (end of list ) |
Current value is 4 at address of 215c040 <-+ |
Address of next value 5 is : 215b010 ->-->-|-+
Current value is 3 at address of 215c060 |
Address of next value 4 is : 215c040 ->-->-+
Current value is 2 at address of 215c080
Address of next value 3 is : 215c060
Current value is 1 at address of 215c0a0
Address of next value 2 is : 215c080
✌
✆
Above output is analyse in pair of output line. First line givens the stored value and
memory address where it is stored. Second line gives the address of previous linked
element. We can add a node by pushing a value at the beginning of the linked list. For
example, here we take a linked list like
4
0×042a
0×1225 7
0×1225
0×a22c 9
0×a22c
0×a2cc
myP
NULL
and we want to add data 6 at the beginning of the linked list. Initially the memory
address of ‘myP’ pointer is ‘0×042a’. A new linked block (‘myNode’) is created as shown
below. Data (value 6) is pushed (at ‘0×d425’ say). The initial pointer address of ‘myP’ is
linked to the ‘nextPtr’ of newly created block and ‘myP’ is assigned the address of this
created block. I.e. now ‘myP’ is pointing to ‘0×042a’.
6
0×d425
0×042a
4
0×042a
0×1225 7
0×1225
0×a22c 9
0×a22c
0×a2cc
myP
NULL
438 File & Data Structure
The C code for pushing data at the beginning of the linked list are given below:
✞
#include <stdio.h>
2 #include <stdlib.h>
4 struct myNode {
int data ;
6 struct myNode *nextPtr ;
};
8
void Push (struct myNode ** myP , int value) {
10 struct myNode* childNode = 
(struct myNode*) 
12 malloc(sizeof (struct myNode));
childNode ->data = value;
14 childNode ->nextPtr = (* myP);
(* myP) = childNode ;
16 }
18 void printList (struct myNode *currentNodePtr ) {
while (currentNodePtr != NULL ) {
20 printf(" %d ", currentNodePtr ->data );
currentNodePtr = currentNodePtr ->nextPtr;
22 }
}
24
int main () {
26 struct myNode* head = NULL ;
Push (& head , 9);
28 Push (& head , 7);
Push (& head , 4);
30 Push (& head , 6);
printf("Linked list is: ");
32 printList (head );
return 0;
34 }
✌
✆
✞
Linked list is: 6 4 7 9
✌
✆
We can insert a node by adding a value inbetween of the linked list. For example, here
we take a linked list like
4
0×042a
0×1225 7
0×1225
0×a22c 9
0×a22c
0×a2cc
myP
NULL
3.3. DATA STRUCTURES 439
and we want to add data 6 inbetween of the linked list. A new linked block (‘myNode’)
is created after the second list element as shown below. Data (value 6) is inserted (at
‘0×d425’ say). The ‘nextPtr’ of newly created block is assigned the address of data of 3rd
element. Address of inserted data of the newly inserted block is assigned to the ‘nextPtr’
of 2nd
element of the linked list.
4
0×042a
0×1225 7
0×1225
0×d425
6
0×d425
0×a22c
9
0×a22c
0×a2cc
myP
NULL
The C code for pushing data at the beginning of the linked list are given below:
✞
1 #include <stdio.h>
#include <stdlib.h>
3
struct myNode {
5 int data ;
struct myNode *nextPtr ;
7 };
9 void Push (struct myNode ** myP , int value) {
struct myNode* childNode = 
11 (struct myNode*) 
malloc(sizeof (struct myNode));
13 childNode ->data = value;
childNode ->nextPtr = (* myP);
15 (* myP) = childNode ;
}
17
void Insert(struct myNode* NodeIndex , int value) {
19 if (NodeIndex == NULL ) {
printf("Node index cannot be NULL ");
21 return;
}
23 struct myNode* childNode = 
(struct myNode*) 
25 malloc(sizeof (struct myNode));
childNode ->data = value;
27 childNode ->nextPtr = NodeIndex -> nextPtr;
NodeIndex ->nextPtr = childNode ;
29 }
31 void printList (struct myNode *currentNodePtr ) {
while (currentNodePtr != NULL ) {
440 File & Data Structure
33 printf(" %d ", currentNodePtr ->data );
currentNodePtr = currentNodePtr ->nextPtr;
35 }
}
37
int main () {
39 struct myNode* head = NULL ;
Push (& head , 9);
41 Push (& head , 7);
Insert(head ->nextPtr , 6);
43 Push (& head , 4);
printf("Linked list is: ");
45 printList (head );
return 0;
47 }
✌
✆
✞
Linked list is: 4 6 7 9
✌
✆
Similarly, we can append elements in a linked list. The C code for appending elements in
linked list are given below:
✞
1 #include <stdio.h>
#include <stdlib.h>
3
struct myNode {
5 int data ;
struct myNode *nextPtr ;
7 };
9 void Push (struct myNode ** myP , int value) {
struct myNode* childNode = 
11 (struct myNode*) 
malloc(sizeof (struct myNode));
13 childNode ->data = value;
childNode ->nextPtr = (* myP);
15 (* myP) = childNode ;
}
17
void Append(struct myNode ** myP , int value) {
19 struct myNode* childNode = 
(struct myNode*) 
21 malloc(sizeof (struct myNode));
struct myNode *last = *myP;
23 childNode ->data = value;
childNode ->nextPtr = NULL ;
25 if (* myP == NULL ) {
*myP = childNode ;
27 return;
}
29 while (last ->nextPtr != NULL )
last = last ->nextPtr ;
3.3. DATA STRUCTURES 441
31 last -> nextPtr = childNode ;
return;
33 }
35 void printList (struct myNode *currentNodePtr ) {
while (currentNodePtr != NULL ) {
37 printf(" %d ", currentNodePtr ->data );
currentNodePtr = currentNodePtr ->nextPtr;
39 }
}
41
int main () {
43 struct myNode* head = NULL ;
Push (& head , 7);
45 Push (& head , 1);
Append (&head , -15);
47 Push (& head , 10);
Append (&head , -45);
49 Push (& head , 7);
Push (& head , -5);
51 printf("Linked list is: ");
printList (head );
53 return 0;
}
✌
✆
✞
Linked list is: -5 7 10 1 7 -15 -45
✌
✆
To delete an element from a linked list, we just bypass the elements being deleted as
shown in the following figures.
4
0×042a
0×1225 7
0×1225
0×a22c 9
0×a22c
0×a2cc
myP
NULL
We have a link list as shown above and we want to delete element having value 7. To
do so, we just skip this element and linked first element with third element. as shown
below:
4
0×042a
0×a22c 7
0×1225
0×a22c 9
0×a22c
0×a2cc
myP
NULL
The C code for appending elements in linked list are given below:
442 File & Data Structure
✞
1 #include <stdio.h>
#include <stdlib.h>
3
struct myNode {
5 int data ;
struct myNode *nextPtr ;
7 };
9 void Push (struct myNode ** myP , int value) {
struct myNode* childNode = 
11 (struct myNode*) 
malloc(sizeof (struct myNode));
13 childNode ->data = value;
childNode ->nextPtr = (* myP);
15 (* myP) = childNode ;
}
17
void deleteNode (struct myNode ** head_ref , int key) {
19 struct myNode* temp = *head_ref , *prev ;
if (temp != NULL && temp ->data == key) {
21 * head_ref = temp ->nextPtr;
free (temp );
23 return;
}
25 while (temp != NULL && temp ->data != key) {
prev = temp ;
27 temp = temp ->nextPtr ;
}
29 if (temp == NULL ) return;
prev -> nextPtr = temp ->nextPtr;
31 free (temp );
}
33
void printList (struct myNode *currentNodePtr ) {
35 while (currentNodePtr != NULL ) {
printf(" %d ", currentNodePtr ->data );
37 currentNodePtr = currentNodePtr ->nextPtr;
}
39 }
41 int main () {
struct myNode* head = NULL ;
43 Push (& head , 9);
Push (& head , 7);
45 Push (& head , 4);
printf("Created Linked list is: ");
47 printList (head );
deleteNode (&head , 4);
49 printf("nCreated Linked list is: ");
printList (head );
3.3. DATA STRUCTURES 443
51 return 0;
}
✌
✆
✞
Created Linked list is: 4 7 9
Created Linked list is: 7 9
✌
✆
3.3.7 Heap
A heap is a specialized tree-based data structure that satisfies the heap property that if P
is a parent node of C, then the key (the value) of P is either greater than or equal to (in
a max heap) or less than or equal to (in a min heap) the key of C. The node at the “top”
of the heap (with no parents) is called the root node. The heap is one maximally efficient
implementation of an abstract data type called a priority queue, and in fact priority
queues are often referred to as “heaps”, regardless of how they may be implemented.
100
193 36
17 2 25 1
2 7
Heaps are implemented in an array of either fixed size or of dynamic size. Each heap
is required to perform internal operation during the insertion, deletion or appending of an
element. The most common form of heap is binary heap. Binary heaps are represented
by using an array only.
0
1 2
3 4 5 6
7 8 9 10
0 1 2 3 4 5 6 7 8 9 10
Figure 3.4: Zero-based Array.
The first or last element of the array is root. The next two elements of the array
contain its children. The next four contain the four children of the two child nodes, etc.
Thus the children of the node at position n would be at positions 2n and 2n + 1 if index
444 File & Data Structure
of the first element of an array is started with one, or 2n + 1 and 2n + 2 if index of the
first element of an array is started with zero.
1
2 3
4 5 6 7
8 9 10 11
1 2 3 4 5 6 7 8 9 10 11
Figure 3.5: One-based Array.
Construction
One dimensional array based heap is constructed by creating an array of requisite size as
shown below:
✞
int myHeap [20]; // heap of size of 20 elements
✌
✆
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
index
Each heap cell is of four bytes size and one-based indexed. We can add twenty elements
in these cells.
Add/Insert an Element
Let an element is being added in the one-base array at the index of 2n. This element is
compared with all previous corresponding child nodes at index locations given by n = n/2.
If value at a child node is greater than the element being added/inserted, it is swapped
mutually. This process undergo until the element is not become greater than the value
at previous child node. Consider an one-based one dimensional array as shown below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
index
2 4 6 9
3
Let current element 3 is being added at the index location 16. Now, 3 is compared
with value at index location 16/2 = 8, i.e. with value 9. Here, 3 < 9, hence 9 is placed in
the index location 16 and 3 is being try to put at index location 8 as shown below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
index
2 4 6 9
3
3.3. DATA STRUCTURES 445
Now, 3 is being put at the index location 16/2 = 8, but before inserting it at this
location, we again compare it with the value stored at index location 8/2 = 4. So, again
3 < 6, hence 6 is placed at the index location 8 as shown below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
index
2 4 6 9
3
This process is iterated until 3 became larger than value at previous child node. Now,
3 is being put at the index location 8/2 = 4, but before inserting it at this location, we
again compare it with the value stored at index location 4/2 = 2. So, again 3 < 4, hence
4 is placed at the index location 4 as shown below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
index
2 4 6 9
3
Finally, 3 became larger than its previous corresponding child node where value 2 is
stored. So, 3 is placed at index location 2 as shown below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
index
2 3 4 6 9
The equivalent code example is given below:
✞
1 void Insert(int v) {
heapSize ++;
3 heap [ heapSize ] = v;
int current_node = heapSize ;
5 while (heap [current_node / 2] > v) {
heap [current_node ] = heap [current_node / 2];
7 current_node /= 2;
}
9 heap [ current_node ] = v;
}
✌
✆
Remove an Element
In heap an element can be deleted, but after each removal of an element, the heap is
reorganized. Consider a one-based one-dimensional heap array as shown below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
index
2 3 4 6 9
Suppose we want to remove the element 4 at index location 4. To do this, we first
remove it from the list as shown below:
446 File & Data Structure
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
index
2 3 6 9
Now, we should have rearrange all the elements right side to the element being re-
moved, i.e. element at index location 8 shall be shifted to index location 4 and element
at index location 16 shall be shifted to index location 8 and so on.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
index
2 3 6 9
Finally, the new heap list shall be looked like as given below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
index
2 3 6 9
3.3.8 Tree
Binary tree is the data structure to maintain data into memory of program. There exists
many data structures but they are used as per their performance. In binary tree, each
node can have two child nodes and each child node can itself be a small binary tree.
1
3 4
7 6 9 8
In this binary tree, we add a child node to a parent node. Child nodes have the
reference to their parent node. By this way each child node is linked with its parent node
& parent node is linked with its parent node and so on.
Create Tree Structure
Here, we have create a coordinate based tree nodes. A node contains the parent’s coor-
dinate, current node coordinate and node value. The node structure is like (xold, yold,
xnew, ynew, value). For it, a structure is created as shown below:
✞
struct TreeData {
2 int x_node;
int y_node;
4 int x_child_node ;
int y_child_node ;
3.3. DATA STRUCTURES 447
6 int val;
};
8
/* Current node coordinates .*/
10 struct NewCoord {
int x;
12 int y;
} nc;
✌
✆
Insert Tree Data
First we get the new coordinate of current node, i.e. child node. The value is linked with
parent node and saved in a data file. A node is in a sequential structure of xold, yold,
xnew, ynew, value.
✞
1 int insert(struct TreeData *td , FILE *fp , int x_node , int y_node ,
int val) {
int xnew ;
3 int ynew ;
xnew = nc.x + 1;
5 ynew = nc.y + 1;
if (xnew < x_node || ynew < y_node) {
7 return 1;
}
9 td ->x_node = x_node;
td ->y_node = y_node;
11 td ->x_child_node = xnew ;
td ->y_child_node = ynew ;
13 td ->val = val;
fwrite(td , sizeof ( struct TreeData ), 1, fp);
15 nc.x = xnew ;
nc.y = ynew ;
17 return 0;
}
✌
✆
Display Tree Data
Here we search all the child nodes and values of the parent node (xold, yold). Scann the
file and put the output in console when parent node is equal to the supplied parent node.
✞
int view ( struct TreeData *td , FILE *fp , int x_node , int y_node) {
2 printf("%10s%10s%10s%10s%10sn",
"parent x",
4 "parent y",
"child x",
6 "child y",
"Value");
8 printf("%50sn"," ------------------------------------------------");
int s;
448 File & Data Structure
10 s = fread(td , sizeof (struct TreeData ), 1, fp);
while (s > 0) {
12 if (td ->x_node == x_node && td ->y_node == y_node) {
printf("%10d%10d%10d%10d%10dn",
14 td ->x_node ,
td ->y_node ,
16 td -> x_child_node ,
td -> y_child_node ,
18 td ->val);
}
20 s = fread(td , sizeof (struct TreeData ), 1, fp);
}
22 return 0;
}
✌
✆
Delete Tree Data
In this step, we search the required parent node whose child node values are to be emptied.
First the data from data file is saved into temporary file with deleted values of all child
nodes. Original file is deleted and temporary file is renamed to the data file.
✞
1 int delete(struct TreeData *td , FILE *fp , int x_node , int y_node) {
int s;
3 FILE *tmp;
tmp = fopen("Tmp.txt", "wb");
5 s = fread(td , sizeof (struct TreeData ), 1, fp);
while (s > 0) {
7 if (td ->x_node == x_node && td ->y_node == y_node) {
td ->val = 0;
9 fwrite(td , sizeof (struct TreeData ), 1, tmp);
} else {
11 fwrite(td , sizeof (struct TreeData ), 1, tmp);
}
13 s = fread(td , sizeof (struct TreeData ), 1, fp);
}
15 fclose(tmp);
remove(fp);
17 rename("Tmp.txt", " TreeNode .txt");
return 0;
19 }
✌
✆
Here is complete code for data tree.
✞
1 #include <stdio.h>
3 /* Three data structure . x_node & y_node *
*represents to the parent node . While *
5 *x_child_node & y_child_node represents *
*to the child node . val is data value at*
7 *child node . Parent node is link of the*
3.3. DATA STRUCTURES 449
*child node .*/
9 struct TreeData {
int x_node;
11 int y_node;
int x_child_node ;
13 int y_child_node ;
int val;
15 };
17 /* Current node coordinates .*/
struct NewCoord {
19 int x;
int y;
21 } nc;
23 /* Insert data at current child node ,*
*linked with its parent node . */
25 int insert(struct TreeData *td , FILE *fp ,
int x_node , int y_node , int val) {
27 int xnew ;
int ynew ;
29 xnew = nc.x + 1;
ynew = nc.y + 1;
31 if (xnew < x_node || ynew < y_node) {
return 1;
33 }
td ->x_node = x_node;
35 td ->y_node = y_node;
td ->x_child_node = xnew ;
37 td ->y_child_node = ynew ;
td ->val = val;
39 fwrite(td , sizeof ( struct TreeData ), 1, fp);
nc.x = xnew ;
41 nc.y = ynew ;
return 0;
43 }
45 /* View all the child nodes of the parent node .*/
int view ( struct TreeData *td , FILE *fp , int x_node , int y_node) {
47 printf("%10s%10s%10s%10s%10sn",
"parent x",
49 "parent y",
"child x",
51 "child y",
"Value");
53 printf("%50sn"," ------------------------------------------------");
int s;
55 s = fread(td , sizeof (struct TreeData ), 1, fp);
while (s > 0) {
57 if (td ->x_node == x_node && td ->y_node == y_node) {
printf("%10d%10d%10d%10d%10dn",
450 File & Data Structure
59 td ->x_node ,
td ->y_node ,
61 td -> x_child_node ,
td -> y_child_node ,
63 td ->val);
}
65 s = fread(td , sizeof (struct TreeData ), 1, fp);
}
67 return 0;
}
69
/* Delete all values at parent node .*/
71 int delete(struct TreeData *td , FILE *fp ,
int x_node , int y_node) {
73 int s;
FILE *tmp;
75 tmp = fopen("Tmp.txt", "wb");
s = fread(td , sizeof (struct TreeData ), 1, fp);
77 while (s > 0) {
if (td ->x_node == x_node && td ->y_node == y_node) {
79 td ->val = 0;
fwrite(td , sizeof (struct TreeData ), 1, tmp);
81 } else {
fwrite(td , sizeof (struct TreeData ), 1, tmp);
83 }
s = fread(td , sizeof (struct TreeData ), 1, fp);
85 }
fclose(tmp);
87 remove(fp);
rename("Tmp.txt", " TreeNode .txt");
89 return 0;
}
91
/* Main function part .*/
93 int main () {
FILE *fp;
95 struct TreeData td;
/* Open file and write tree data .*/
97 fp = fopen("TreeNode .txt", "wb+");
int i = 0;
99 while (i < 100) {
insert (&td , fp , i % 5, i % 6, i);
101 i++;
}
103 fclose(fp);
/* Open file and Delete specific tree node data .*/
105 fp = fopen("TreeNode .txt", "rb");
delete (&td , fp , 1, 1);
107 fclose(fp);
/* Open file and view tree node data .*/
109 fp = fopen("TreeNode .txt", "rb");
3.3. DATA STRUCTURES 451
view (&td , fp , 1, 1);
111 fclose(fp);
return 0;
113 }
✌
✆
3.3.9 Binary Tree
452 Miscellaneous
4.1. ERROR HANDLING FUNCTIONS 453
4Miscellaneous
4.1 Error Handling Functions
Following functions are used for handling of errors arises when a program is compiled or
executed. Some of the errors are thrown by compiler when a program is compiles. These
errors arise if we try to use undefined functions, misprints or using wrong procedures. Run
time errors arise when we try to access restricted or denied memory locations, try to create
a wrong file structure or wrote a program which is not compatible to hardware/software.
4.1.1 clearerr function
The synopsis of the function is
✞
1 #include <stdio.h>
void clearerr (FILE *stream);
✌
✆
The clearerr function clears the end-of-file and error indicators for the stream pointed-by
‘stream’. A simple example is
✞
#include <stdio.h>
2
int main () {
4 FILE * fName;
fName = fopen("F.txt", "r");
6 if (fName == NULL )
perror("Can not open the file ");
8 else {
fputc(’x’, fName);
10 if (ferror(fName)) {
printf("Can not write in file .n");
12 clearerr (fName);
}
14 fgetc(fName);
if (! ferror(fName))
16 printf("Reading from file .n");
fclose(fName);
18 }
return 0;
20 }
✌
✆
✞
Can not write in file .
Reading from file .
✌
✆
454 Miscellaneous
4.1.2 ferror function
The synopsis of the function is
✞
#include <stdio.h>
2 int ferror(FILE *stream);
✌
✆
The ferror function tests the error indicator for the stream pointed-by ‘stream’ and returns
nonzero if and only if the error indicator is set for stream, otherwise it returns zero. A
simple example is
✞
#include <stdio.h>
2
int main (void ) {
4 int a;
FILE *fp;
6 /* file .txt must be in executable ’s dir*/
fp = fopen("file .txt", "rb");
8 /* Read single ints at a time , stopping on EOF or error:*/
while (fread(&a, sizeof (int), 1, fp), !feof (fp) &&
!ferror(fp)){
10 printf("I read %dn", a);
}
12 if (feof (fp))
printf("End of file was reached .n");
14 if (ferror(fp))
printf("An error occurred .n");
16 fclose(fp);
return 0;
18 }
✌
✆
✞
I read 1735287116
I read 1701279073
End of file was reached .
✌
✆
4.1.3 perror function
The synopsis of the function is
✞
1 #include <stdio.h>
void perror(const char *s);
✌
✆
The perror function maps the error number in the integer expression errno to an error
message. It writes a sequence of characters to the standard error stream thus: first,
if ‘s’ is not a null pointer and the character pointed-by ‘s’ is not the null character,
the string pointed-by ‘s’ followed by a colon (:) and a space; then an appropriate error
message string followed by a new-line character. The contents of the error message are
the same as those returned by the strerror function with the argument errno, which are
implementation-defined. A simple example is
4.1. ERROR HANDLING FUNCTIONS 455
✞
#include <stdio.h>
2 /* Must include to see " errno"*/
#include <errno.h>
4
int main (void ) {
6 if (fseek(stdin , 10L, SEEK_SET ) < 0)
perror("fseek");
8 /* Stop using this stream */
fclose(stdin);
10 if (fseek(stdin , 20L, SEEK_CUR ) < 0) {
if (errno == EBADF) {
12 perror("fseek again , EBADF");
} else {
14 perror("fseek again");
}
16 }
return 0;
18 }
✌
✆
✞
fseek: Illegal seek
fseek again , EBADF: Bad file descriptor
✌
✆
4.1.4 Segmentation Fault
Segmentation fault is shown by different hardware and operating system with different
ways. Some prominent reason of segmentation fault are
1. Dereferencing null pointers.
2. Accessing non existent pointer.
3. Attempting to access a nonexistent memory address.
4. Attempting to access memory the program does not have rights to.
5. Attempting to write read-only memory.
6. Dereferencing or assigning to an uninitialized pointer.
7. Dereferencing or assigning to a freed pointer.
8. A buffer overflow.
9. A stack overflow.
10. Attempting to execute a program that does not compile correctly.
456 Miscellaneous
✞
#include <stdio.h>
2
int main () {
4 FILE *fl; /* File pointer */
fclose (fl);/* Trying to close file pointer *
6 * that was never opened before. *
* Cause for segmentation fault. */
8 return 0; /* Return sucess. */
}
✌
✆
4.2 Reserved Keyword
There are 32 keywords in C89 while 37 reserve keywords in C99 and 44 reserve keywords
in C11. These keywords are solely reserved for internal use by C compilers. They can not
be redefined by programmer or can not be used as literals. The list of reserved keywords
is given below.
auto double int static
break else long struct
case enum register switch
char extern restrict union
const float return unsigned
continue for short void
default goto signed volatile
do if sizeof while
Bool Complex Imaginary inline
restrict
Alignas Alignof Atomic Generic
Noreturn Static assert Thread local
4.3 Case Sensitivity
C identifiers are case sensitive i.e. myname, MYNAME, and MyName are the names
of three different objects. Some linker may map external identifiers to a single case,
although this is uncommon in most modern linker. See the following example, in which
two variables ‘y’ and ‘Y’ are declared and initialized. They are treated as two different
variables and can be accessed differently.
✞
1 #include <stdio.h>
3 int main () {
// Declare a variable y
5 int y = 1;
// Declare a variable Y
7 int Y = 2;
printf("y is %d and Y is %dn", y, Y);
4.4. COMMENTING 457
9 return 0;
}
✌
✆
✞
y is 1 and Y is 2
✌
✆
4.4 Commenting
Commenting inside the C code is a beautiful feature of C language. It provides the utility
for writing managed codes. Commenting occurs within the C codes. It may be of a single
line or can span in multiple lines. There are two way of commenting. First is single line
commenting which started with ‘//’. Anything written in the line started with ‘//’ are
skipped by the C compilers. Presence of another ‘//’ in the same line does not end the
single line comment. Second method is multi-line commenting. Text starting with the
token ‘/*’ are treated as a comments and ignored. The multi-line comments are ended at
next token ‘*/’.
✞
1 #include <stdio.h>
3 int main () {
// Declare a variable // as y
5 int y;
/* <-- given expression *
7 *y = (5 + 3 - 4) % 2 *
*is computed in steps*
9 *y = (8 - 4) % 2 *
*y = 4 % 2 = 0 -->*/
11 y = (5 + 3 - 4) % 2;
printf("Result is : %dn", y);
13 return 0;
}
✌
✆
✞
Result is : 0
✌
✆
458 Library
5.1. THROUGH NETBEAN 459
5Library
In computer science, there are two types libraries. (i) A static library is a collection of
object files which contain library routines and data. It is built in such a way that the
link editor will incorporate a copy of only those object files that hold the functions and
data referenced in the program into the executable at link time. (ii) A shared library is a
shared object file that contains functions and data. It is built in such a way that the link
editor will only store in the executable the name of the shared library and information
about the symbols referenced by the executable. At run time the dynamic linker, a.k.a.
the program interpreter in ELF, will map the shared library into the virtual address space
of the process image of the executable and resolve by name the symbols in the shared
library used by the executable. That is process is also called dynamic linking. Here, we
will write example code for linking static libraries in C. There are three steps of static
library use. First is generation of library, second is linking of library and third is its
application.
5.1 Through NetBean
5.1.1 Create Library
To create a library first create a C static or dynamic library project “myLib” in Netbean
with cygwin gcc compiler. Create two files, myFunc.c and myFunc.h within the “myLib”
project. The codes of these two files are respectively
✞
1 #include <stdio.h>
3 void myFunc(void ){
puts ("Hello , I’m a shared library ");
5 }
✌
✆
✞
1 #ifndef MYFUNC_H
#define MYFUNC_H
3
#ifdef __cplusplus
5 extern "C" {
#endif
7
// static library function
9 extern void myFunc(void );
11 #ifdef __cplusplus
}
13 #endif
460 Library
15 #endif /* MYFUNC_H */
✌
✆
Open project properties and click on C-Compiler or Linker option. Set tool to “gcc -
shared”. Here, keyword “-shared” makes a library shareble. Compile this library and you
will get a library for use with other program.
5.1.2 Link Library
Now create second project in Netbean with MinGW, say ‘myProg’. Copy your generated
library in this new project (say ‘myProg’) from where you can use it. Open the project
property and go to the linker and add following to linker:
✞
1 gcc -L"<path to library >" -l<static/ dynamic lib name >
✌
✆
Here, ‘path to library’ is absolute path of your generated library that is put within your
‘myProg’ project or else where. Copy ‘myFunc.h’ into source directory of this new project
and create new “main.c” file. The code of main file are
✞
1 #include <stdio.h>
#include "myFunc.h"
3
int main (void ) {
5 puts ("This is a shared library test ...");
myFunc ();
7 return 0;
}
✌
✆
Compile and build this program with MinGW gcc compiler and run this program. You
will get the desire output.
✞
This is a shared library test ...
Hello , I’m a shared library
✌
✆
5.2 From Command Line
5.2.1 Create Library
Create two files, myFunc.c and myFunc.h with following codes and put them under a
directory (say “C:
myLib”) that is accessible to you.
✞
#include <stdio.h>
2
void myFunc(void ){
4 puts ("Hello , I’m a shared library ");
}
✌
✆
5.2. FROM COMMAND LINE 461
✞
1 #ifndef MYFUNC_H
#define MYFUNC_H
3
#ifdef __cplusplus
5 extern "C" {
#endif
7
// static library function
9 extern void myFunc(void );
11
#ifdef __cplusplus
13 }
#endif
15
#endif /* MYFUNC_H */
✌
✆
From the command prompt, we can create static and dynamic libraries by using following
commands with cygwin gcc.
✞
gcc -fPIC -c -o myFunc.o myFunc.c -I"C: myLib"
2 gcc -shared -o libmyFunc .dll myFunc.o
✌
✆
Here, ‘-fPIC’ tells GCC that to create Position Independent Code using relative addresses
rather than absolute addresses because these libraries can be loaded multiple times. Here,
this flag may be omitted. If environment for ‘gcc’ compiler is not registered then use
absolute path of the gcc executable like “C:
MinGW
bin
gcc.exe”. ‘-I’ flag is used to add the directory where relevant header files are placed. Here,
the prefix “lib” to ‘myFunc.dll’ required when we link this library to a program during
program’s compilation with ‘-l’ flag identifier. Now out library is ready to be used.
5.2.2 Link Library
Write a new program file “main.c”. The code of main file are
✞
#include <stdio.h>
2 #include "myFunc.h"
4 int main (void ) {
puts ("This is a shared library test ...");
6 myFunc ();
return 0;
8 }
✌
✆
Copy ‘myFunc.h’ into the same directory (say “C:
myLib”) where this code file is placed. Now, compile this program file with MinGW gcc
compiler as command given below:
462 Library
✞
gcc -c -o main .o main .c -I"C: myLib"
2 gcc -o main .exe main .o -L"C: myLib" -lmyFunc
✌
✆
Here, “-L” flag represents to library path where user’s library is placed. “-l” represents
to linked library name with the user’s program. “-I” represents to include path of header
files. Name of static or dynamic library is supplied without prefix “lib” and extension
name “.dll”. The flag ‘-l’ searches for the named library by pre-pending ‘lib’ automatically.
If libraries are placed in the same directory (say “C:
myLib”) where program file is then use following modified command:
✞
gcc -o main .exe main .o ./ -lmyFunc
✌
✆
The output of above program is
✞
This is a shared library test ...
Hello , I’m a shared library
✌
✆
Here, both static and dynamic libraries can be used with C program. But dynamic
libraries are preferred over the static libraries as and when dynamic libraries are upgraded,
program does not need recompilation with upgraded dynamic libraries.
5.3 Load Library Dynamically
In C programming, with POSIX system, we can load a library dynamically by using
functions dlopen(), dlsym() and dlclose(). These functions are found in ‘dlfcn.h’. Note
that this library only loaded library function for its calling. It does not check input and
output parameters. Parameters are checked by function itself when it is called.
dlopen This function is used to open a static or dynamic library from user’s directory
and reading of its export table that contains the function names of the library. It accepts
two arguments. First is library name with absolute/relative path and second is mode
of opening of the library. It returns a ‘handle’ pointing to the library. If it is unable
to locate/open a file, it returns NULL or an error value. If NULL is used as file name
argument to this function, then it will export symbols in the executable for currently
loaded shared libraries via dlsym function.
✞
void *myLib = dlopen(<name >, <mode >)
✌
✆
Here name of library is constant character type and mode of opening of library is either
of the ‘RTLD NOW’ (for immediate function binding), ‘RTLD LAZY’ (for lazy function
binding), ‘RTLD GLOBAL’ or ‘RTLD LOCAL’. See the example below:
✞
1 #include <stdio.h>
#include <stdlib.h>
3 #include <dlfcn.h>
5 int main () {
void * myLib;
5.3. LOAD LIBRARY DYNAMICALLY 463
7 myLib = dlopen("libcdy.dll", RTLD_LAZY );
if (myLib == NULL ) {
9 printf("Can not locate library %sn", "libcdy.dll");
}
11 return EXIT_SUCCESS ;
}
✌
✆
dlsym After a shared library is loaded into the address space of the running process,
this function is used to obtain the address of an exported symbol in that shared library.
We can now access the function or data through the address returned from dlsym function.
This function searches for the function supplied it to as its second argument and returns
its address. If the function could not be found, it returns NULL. The return value must
be casted to a proper function pointer before it can be used. Its syntax is looked like as
✞
void (* fptr )();
2 fptr = dlsym(<handle >, <function name >);
✌
✆
See the example below:
✞
#include <stdio.h>
2 #include <stdlib.h>
#include <dlfcn.h>
4
int main () {
6 void * myLib;
void (* fptr )();
8 myLib = dlopen("libcdy.dll", RTLD_LAZY );
if (myLib != NULL ) {
10 fptr = dlsym(myLib , "myFunc");
if (! fptr ) {
12 printf("Can not locate function %sn", "myFunc");
}
14 /* Call the function through its pointer */
fptr ();
16 } else {
printf("Error in opening %s library !!", "libcdy.dll");
18 }
if (myLib != NULL )
20 dlclose (myLib);
return EXIT_SUCCESS ;
22 }
✌
✆
dlclose Each handle opened with dlopen() function must be closed by using dlclose()
function. This function returns ‘-1’ if it failed to close a handle refering to the opened
library.
✞
int v= dlclose (<handle >);
✌
✆
464 Library
dlerror This function is used to retrieve a text message that is describing to the most
recent error occurred during the process of either of the functions dlopen(), dlsym() and
dlclose().
✞
1 char *v= dlerror(void );
✌
✆

More Related Content

What's hot

What's hot (20)

C tech questions
C tech questionsC tech questions
C tech questions
 
C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2
 
C++ Pointers
C++ PointersC++ Pointers
C++ Pointers
 
Fp201 unit5 1
Fp201 unit5 1Fp201 unit5 1
Fp201 unit5 1
 
C++ L05-Functions
C++ L05-FunctionsC++ L05-Functions
C++ L05-Functions
 
C++ L07-Struct
C++ L07-StructC++ L07-Struct
C++ L07-Struct
 
C++ L06-Pointers
C++ L06-PointersC++ L06-Pointers
C++ L06-Pointers
 
C++ Programming - 11th Study
C++ Programming - 11th StudyC++ Programming - 11th Study
C++ Programming - 11th Study
 
C++ L04-Array+String
C++ L04-Array+StringC++ L04-Array+String
C++ L04-Array+String
 
Stl algorithm-Basic types
Stl algorithm-Basic typesStl algorithm-Basic types
Stl algorithm-Basic types
 
C aptitude scribd
C aptitude scribdC aptitude scribd
C aptitude scribd
 
Container adapters
Container adaptersContainer adapters
Container adapters
 
Inheritance and polymorphism
Inheritance and polymorphismInheritance and polymorphism
Inheritance and polymorphism
 
Static and const members
Static and const membersStatic and const members
Static and const members
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Lecture#8 introduction to array with examples c++
Lecture#8 introduction to array with examples c++Lecture#8 introduction to array with examples c++
Lecture#8 introduction to array with examples c++
 
C++ L03-Control Structure
C++ L03-Control StructureC++ L03-Control Structure
C++ L03-Control Structure
 
Implementing stack
Implementing stackImplementing stack
Implementing stack
 
C++ L08-Classes Part1
C++ L08-Classes Part1C++ L08-Classes Part1
C++ L08-Classes Part1
 
functions of C++
functions of C++functions of C++
functions of C++
 

Similar to Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by Arun Umrao

#include iostream #include cstring #include vector #i.pdf
 #include iostream #include cstring #include vector #i.pdf #include iostream #include cstring #include vector #i.pdf
#include iostream #include cstring #include vector #i.pdfanandatalapatra
 
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...GkhanGirgin3
 
Structures in C.pptx
Structures in C.pptxStructures in C.pptx
Structures in C.pptxBoni Yeamin
 
Dns server clients (actual program)
Dns server clients (actual program)Dns server clients (actual program)
Dns server clients (actual program)Youssef Dirani
 
Dns server clients (actual program)
Dns server clients (actual program)Dns server clients (actual program)
Dns server clients (actual program)Youssef Dirani
 
DS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docxDS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docxVeerannaKotagi1
 
Easy Understanding of Structure Union Typedef Enum in C Language.pdf
Easy Understanding of Structure Union Typedef Enum in C Language.pdfEasy Understanding of Structure Union Typedef Enum in C Language.pdf
Easy Understanding of Structure Union Typedef Enum in C Language.pdfsudhakargeruganti
 
I have the following code and I need to know why I am receiving the .pdf
I have the following code and I need to know why I am receiving the .pdfI have the following code and I need to know why I am receiving the .pdf
I have the following code and I need to know why I am receiving the .pdfezzi552
 
VTU DSA Lab Manual
VTU DSA Lab ManualVTU DSA Lab Manual
VTU DSA Lab ManualAkhilaaReddy
 
Dynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxssuser688516
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptxJawadTanvir
 
CHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptxCHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptxGebruGetachew2
 
Getting the following errorsError 1 error C2436 {ctor} mem.pdf
Getting the following errorsError 1 error C2436 {ctor}  mem.pdfGetting the following errorsError 1 error C2436 {ctor}  mem.pdf
Getting the following errorsError 1 error C2436 {ctor} mem.pdfherminaherman
 
So basically I worked really hard on this code in my CS150 class and.pdf
So basically I worked really hard on this code in my CS150 class and.pdfSo basically I worked really hard on this code in my CS150 class and.pdf
So basically I worked really hard on this code in my CS150 class and.pdfeyewaregallery
 
Data structure week 3
Data structure week 3Data structure week 3
Data structure week 3karmuhtam
 

Similar to Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by Arun Umrao (20)

DS Code (CWH).docx
DS Code (CWH).docxDS Code (CWH).docx
DS Code (CWH).docx
 
#include iostream #include cstring #include vector #i.pdf
 #include iostream #include cstring #include vector #i.pdf #include iostream #include cstring #include vector #i.pdf
#include iostream #include cstring #include vector #i.pdf
 
structure,pointerandstring
structure,pointerandstringstructure,pointerandstring
structure,pointerandstring
 
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
 
Structures in C.pptx
Structures in C.pptxStructures in C.pptx
Structures in C.pptx
 
Dns server clients (actual program)
Dns server clients (actual program)Dns server clients (actual program)
Dns server clients (actual program)
 
Dns server clients (actual program)
Dns server clients (actual program)Dns server clients (actual program)
Dns server clients (actual program)
 
DS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docxDS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docx
 
Easy Understanding of Structure Union Typedef Enum in C Language.pdf
Easy Understanding of Structure Union Typedef Enum in C Language.pdfEasy Understanding of Structure Union Typedef Enum in C Language.pdf
Easy Understanding of Structure Union Typedef Enum in C Language.pdf
 
I have the following code and I need to know why I am receiving the .pdf
I have the following code and I need to know why I am receiving the .pdfI have the following code and I need to know why I am receiving the .pdf
I have the following code and I need to know why I am receiving the .pdf
 
dynamic-allocation.pdf
dynamic-allocation.pdfdynamic-allocation.pdf
dynamic-allocation.pdf
 
VTU DSA Lab Manual
VTU DSA Lab ManualVTU DSA Lab Manual
VTU DSA Lab Manual
 
Dynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptx
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
 
CHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptxCHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptx
 
Structures
StructuresStructures
Structures
 
Getting the following errorsError 1 error C2436 {ctor} mem.pdf
Getting the following errorsError 1 error C2436 {ctor}  mem.pdfGetting the following errorsError 1 error C2436 {ctor}  mem.pdf
Getting the following errorsError 1 error C2436 {ctor} mem.pdf
 
So basically I worked really hard on this code in my CS150 class and.pdf
So basically I worked really hard on this code in my CS150 class and.pdfSo basically I worked really hard on this code in my CS150 class and.pdf
So basically I worked really hard on this code in my CS150 class and.pdf
 
Data structure week 3
Data structure week 3Data structure week 3
Data structure week 3
 
C++_notes.pdf
C++_notes.pdfC++_notes.pdf
C++_notes.pdf
 

More from ssuserd6b1fd

Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...
Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...
Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...ssuserd6b1fd
 
Decreasing increasing functions by arun umrao
Decreasing increasing functions by arun umraoDecreasing increasing functions by arun umrao
Decreasing increasing functions by arun umraossuserd6b1fd
 
Distribution of normal data understanding it numerical way by arun umrao
Distribution of normal data   understanding it numerical way by arun umraoDistribution of normal data   understanding it numerical way by arun umrao
Distribution of normal data understanding it numerical way by arun umraossuserd6b1fd
 
Decreasing and increasing functions by arun umrao
Decreasing and increasing functions by arun umraoDecreasing and increasing functions by arun umrao
Decreasing and increasing functions by arun umraossuserd6b1fd
 
What is meaning of epsilon and delta in limits of a function by Arun Umrao
What is meaning of epsilon and delta in limits of a function by Arun UmraoWhat is meaning of epsilon and delta in limits of a function by Arun Umrao
What is meaning of epsilon and delta in limits of a function by Arun Umraossuserd6b1fd
 
Notes for GNU Octave - Numerical Programming - for Students 01 of 02 by Arun ...
Notes for GNU Octave - Numerical Programming - for Students 01 of 02 by Arun ...Notes for GNU Octave - Numerical Programming - for Students 01 of 02 by Arun ...
Notes for GNU Octave - Numerical Programming - for Students 01 of 02 by Arun ...ssuserd6b1fd
 
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...ssuserd6b1fd
 
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...ssuserd6b1fd
 
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...ssuserd6b1fd
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...ssuserd6b1fd
 
Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...
Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...
Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...ssuserd6b1fd
 
Work and Energy Notes by Arun Umrao
Work and Energy Notes by Arun UmraoWork and Energy Notes by Arun Umrao
Work and Energy Notes by Arun Umraossuserd6b1fd
 
Notes of Units, Dimensions & Errors for IIT JEE by Arun Umrao
Notes of Units, Dimensions & Errors for IIT JEE by Arun UmraoNotes of Units, Dimensions & Errors for IIT JEE by Arun Umrao
Notes of Units, Dimensions & Errors for IIT JEE by Arun Umraossuserd6b1fd
 
Physics dictionary for CBSE, ISCE, Class X Students by Arun Umrao
Physics dictionary for CBSE, ISCE, Class X Students by Arun UmraoPhysics dictionary for CBSE, ISCE, Class X Students by Arun Umrao
Physics dictionary for CBSE, ISCE, Class X Students by Arun Umraossuserd6b1fd
 
Java Programming Notes for Beginners by Arun Umrao
Java Programming Notes for Beginners by Arun UmraoJava Programming Notes for Beginners by Arun Umrao
Java Programming Notes for Beginners by Arun Umraossuserd6b1fd
 
Notes of 8085 micro processor Programming for BCA, MCA, MSC (CS), MSC (IT) &...
Notes of 8085 micro processor Programming  for BCA, MCA, MSC (CS), MSC (IT) &...Notes of 8085 micro processor Programming  for BCA, MCA, MSC (CS), MSC (IT) &...
Notes of 8085 micro processor Programming for BCA, MCA, MSC (CS), MSC (IT) &...ssuserd6b1fd
 
Notes of 8051 Micro Controller for BCA, MCA, MSC (CS), MSC (IT) & AMIE IEI- b...
Notes of 8051 Micro Controller for BCA, MCA, MSC (CS), MSC (IT) & AMIE IEI- b...Notes of 8051 Micro Controller for BCA, MCA, MSC (CS), MSC (IT) & AMIE IEI- b...
Notes of 8051 Micro Controller for BCA, MCA, MSC (CS), MSC (IT) & AMIE IEI- b...ssuserd6b1fd
 
Modlica an introduction by Arun Umrao
Modlica an introduction by Arun UmraoModlica an introduction by Arun Umrao
Modlica an introduction by Arun Umraossuserd6b1fd
 
Maxima CAS an introduction
Maxima CAS an introductionMaxima CAS an introduction
Maxima CAS an introductionssuserd6b1fd
 
Maxima & Minima of Functions - Differential Calculus by Arun Umrao
Maxima & Minima of Functions - Differential Calculus by Arun UmraoMaxima & Minima of Functions - Differential Calculus by Arun Umrao
Maxima & Minima of Functions - Differential Calculus by Arun Umraossuserd6b1fd
 

More from ssuserd6b1fd (20)

Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...
Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...
Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...
 
Decreasing increasing functions by arun umrao
Decreasing increasing functions by arun umraoDecreasing increasing functions by arun umrao
Decreasing increasing functions by arun umrao
 
Distribution of normal data understanding it numerical way by arun umrao
Distribution of normal data   understanding it numerical way by arun umraoDistribution of normal data   understanding it numerical way by arun umrao
Distribution of normal data understanding it numerical way by arun umrao
 
Decreasing and increasing functions by arun umrao
Decreasing and increasing functions by arun umraoDecreasing and increasing functions by arun umrao
Decreasing and increasing functions by arun umrao
 
What is meaning of epsilon and delta in limits of a function by Arun Umrao
What is meaning of epsilon and delta in limits of a function by Arun UmraoWhat is meaning of epsilon and delta in limits of a function by Arun Umrao
What is meaning of epsilon and delta in limits of a function by Arun Umrao
 
Notes for GNU Octave - Numerical Programming - for Students 01 of 02 by Arun ...
Notes for GNU Octave - Numerical Programming - for Students 01 of 02 by Arun ...Notes for GNU Octave - Numerical Programming - for Students 01 of 02 by Arun ...
Notes for GNU Octave - Numerical Programming - for Students 01 of 02 by Arun ...
 
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
 
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
 
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...
 
Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...
Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...
Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...
 
Work and Energy Notes by Arun Umrao
Work and Energy Notes by Arun UmraoWork and Energy Notes by Arun Umrao
Work and Energy Notes by Arun Umrao
 
Notes of Units, Dimensions & Errors for IIT JEE by Arun Umrao
Notes of Units, Dimensions & Errors for IIT JEE by Arun UmraoNotes of Units, Dimensions & Errors for IIT JEE by Arun Umrao
Notes of Units, Dimensions & Errors for IIT JEE by Arun Umrao
 
Physics dictionary for CBSE, ISCE, Class X Students by Arun Umrao
Physics dictionary for CBSE, ISCE, Class X Students by Arun UmraoPhysics dictionary for CBSE, ISCE, Class X Students by Arun Umrao
Physics dictionary for CBSE, ISCE, Class X Students by Arun Umrao
 
Java Programming Notes for Beginners by Arun Umrao
Java Programming Notes for Beginners by Arun UmraoJava Programming Notes for Beginners by Arun Umrao
Java Programming Notes for Beginners by Arun Umrao
 
Notes of 8085 micro processor Programming for BCA, MCA, MSC (CS), MSC (IT) &...
Notes of 8085 micro processor Programming  for BCA, MCA, MSC (CS), MSC (IT) &...Notes of 8085 micro processor Programming  for BCA, MCA, MSC (CS), MSC (IT) &...
Notes of 8085 micro processor Programming for BCA, MCA, MSC (CS), MSC (IT) &...
 
Notes of 8051 Micro Controller for BCA, MCA, MSC (CS), MSC (IT) & AMIE IEI- b...
Notes of 8051 Micro Controller for BCA, MCA, MSC (CS), MSC (IT) & AMIE IEI- b...Notes of 8051 Micro Controller for BCA, MCA, MSC (CS), MSC (IT) & AMIE IEI- b...
Notes of 8051 Micro Controller for BCA, MCA, MSC (CS), MSC (IT) & AMIE IEI- b...
 
Modlica an introduction by Arun Umrao
Modlica an introduction by Arun UmraoModlica an introduction by Arun Umrao
Modlica an introduction by Arun Umrao
 
Maxima CAS an introduction
Maxima CAS an introductionMaxima CAS an introduction
Maxima CAS an introduction
 
Maxima & Minima of Functions - Differential Calculus by Arun Umrao
Maxima & Minima of Functions - Differential Calculus by Arun UmraoMaxima & Minima of Functions - Differential Calculus by Arun Umrao
Maxima & Minima of Functions - Differential Calculus by Arun Umrao
 

Recently uploaded

Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 

Recently uploaded (20)

Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 

Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by Arun Umrao

  • 1. 400 File & Data Structure ✞ 1 struct s { int id1; //4 bytes for data 3 int id2; //4 bytes for data };// total size will be equal to sum of all 5 // bytes , upward rounded off to , multiple //to size of largest structure member. ✌ ✆ ✞ #include <stdio.h> 2 struct s { 4 int id1; int id2; 6 }; // Total 8 bytes rounded up to // 4*2=8 bytes is size of s 8 int main () { 10 printf("Size of Structure s in bytes is "); printf("%d.n", sizeof(struct s)); 12 return 0; } ✌ ✆ ✞ Size of Structure s in bytes is 8 ✌ ✆ Here, sum of memory bytes calculated from structure members, is rounded off upward so that it is perfect multiple of the largest data type member of that structure. This is because, number of elements (n) in an array is given by n = Sum of Bytes sizeof(data type) Where n is an integer. If there are multiple datatypes as in the case of a structure, if bytes are not multiple of all member datatypes’ size, then n becomes fraction. This rounding off is done to make structure operation easy. Take another case: ✞ 1 struct s { int id1; //4 bytes for data 3 double id2; //8 bytes for data };// total size will be equal to sum of all 5 // bytes , upward rounded off to , multiple //to size of largest structure member. ✌ ✆ ✞ #include <stdio.h> 2 struct s { 4 int id1; double id2; 6 }; // Total 12 bytes rounded up to // 8*2=16 bytes is size of s
  • 2. 3.3. DATA STRUCTURES 401 8 int main () { 10 printf("Size of Structure s in bytes is "); printf("%d.n", sizeof(struct s)); 12 return 0; } ✌ ✆ ✞ Size of Structure s in bytes is 16 ✌ ✆ ✞ 1 struct s { int id1; //4 bytes for data 3 double *id2; //4 bytes for address };// total size will be equal to sum of all 5 // bytes , upward rounded off to , multiple //to size of largest structure member. ✌ ✆ ✞ #include <stdio.h> 2 struct s { 4 int id1; double *id2; 6 }; // Total 8 bytes rounded up to // 4*2=8 bytes is size of s 8 int main () { 10 printf("Size of Structure s in bytes is "); printf("%d.n", sizeof(struct s)); 12 return 0; } ✌ ✆ ✞ Size of Structure s in bytes is 8 ✌ ✆ Next example ✞ 1 struct s { int id1; //4 bytes for data 3 char id2; //1 byte for data };// total size will be equal to sum of all 5 // bytes , upward rounded off to , multiple //to size of largest structure member. ✌ ✆ ✞ #include <stdio.h> 2 struct s { 4 int id1; char id2; 6 }; // Total 5 bytes rounded up to // 4*2=8 bytes is size of s
  • 3. 402 File & Data Structure 8 int main () { 10 printf("Size of Structure s in bytes is "); printf("%d.n", sizeof(struct s)); 12 return 0; } ✌ ✆ ✞ Size of Structure s in bytes is 8 ✌ ✆ Next example ✞ 1 struct s { char id1; //1 byte for data 3 char id2; //1 byte for data };// total size will be equal to sum of all 5 // bytes , upward rounded off to , multiple //to size of largest structure member. ✌ ✆ ✞ #include <stdio.h> 2 struct s { 4 char id1; char id2; 6 }; // Total 2 bytes rounded up to // 1*2=2 bytes is size of s 8 int main () { 10 printf("Size of Structure s in bytes is "); printf("%d.n", sizeof(struct s)); 12 return 0; } ✌ ✆ ✞ Size of Structure s in bytes is 2 ✌ ✆ Next example ✞ 1 struct s { char *id1; //4 bytes for address 3 char *id2; //4 bytes for address };// total size will be equal to sum of all 5 // bytes , upward rounded off to , multiple //to size of largest structure member. ✌ ✆ ✞ #include <stdio.h> 2 struct s { 4 char *id1; char *id2; 6 }; // Total 8 bytes rounded up to
  • 4. 3.3. DATA STRUCTURES 403 // 4*2=8 bytes is size of s 8 int main () { 10 printf("Size of Structure s in bytes is "); printf("%d.n", sizeof(struct s)); 12 return 0; } ✌ ✆ ✞ Size of Structure s in bytes is 8 ✌ ✆ Next example ✞ 1 struct s { char id1 [5]; //5 bytes for data 3 char id2; //1 byte for data };// total size will be equal to sum of all 5 // bytes , upward rounded off to , multiple //to size of largest structure member. ✌ ✆ ✞ #include <stdio.h> 2 struct s { 4 char id1 [5]; char id2; 6 }; // Total 6 bytes rounded up to // 1*6=6 bytes is size of s 8 int main () { 10 printf("Size of Structure s in bytes is "); printf("%d.n", sizeof(struct s)); 12 return 0; } ✌ ✆ ✞ Size of Structure s in bytes is 6 ✌ ✆ Next example ✞ 1 struct s { char id1 [5]; //5 bytes for data 3 char *id2; //4 bytes for address };// total size will be equal to sum of all 5 // bytes , upward rounded off to , multiple //to size of largest structure member. ✌ ✆ ✞ #include <stdio.h> 2 struct s { 4 char id1 [5]; char *id2;
  • 5. 404 File & Data Structure 6 }; // Total 9 bytes rounded up to // 4*3=12 bytes is size of s 8 10 int main () { printf("Size of Structure s in bytes is "); 12 printf("%d.n", sizeof(struct s)); return 0; 14 } ✌ ✆ ✞ Size of Structure s in bytes is 12 ✌ ✆ Next example ✞ 1 struct s { char id1 [5]; //5 bytes for data 3 double id2; //8 bytes for address };// total size will be equal to sum of all 5 // bytes , upward rounded off to , multiple //to size of largest structure member. ✌ ✆ ✞ #include <stdio.h> 2 struct s { 4 char id1 [5]; double id2; 6 }; // Total 13 bytes rounded up to // 8*2=16 bytes is size of s 8 int main () { 10 printf("Size of Structure s in bytes is "); printf("%d.n", sizeof(struct s)); 12 return 0; } ✌ ✆ ✞ Size of Structure s in bytes is 16 ✌ ✆ Next example ✞ 1 struct s { char id0 [10]; //10 bytes for data 3 char id1 [10]; //10 bytes for data char id2 [11]; //11 bytes for data 5 int id3 [2]; //8 bytes for data int id4 [5]; //20 bytes for data 7 double id5; //8 bytes for address };// total size will be equal to sum of all 9 // bytes , upward rounded off to , multiple //to size of largest structure member. ✌ ✆
  • 6. 3.3. DATA STRUCTURES 405 ✞ #include <stdio.h> 2 struct s { 4 char id0 [10]; char id1 [10]; 6 char id2 [11]; int id3 [2]; 8 int id4 [5]; double id5; 10 }; // Total 67 bytes rounded up to // 8*9=72 bytes is size of s 12 int main () { 14 printf("Size of Structure s in bytes is "); printf("%d.n", sizeof(struct s)); 16 return 0; } ✌ ✆ ✞ Size of Structure s in bytes is 72 ✌ ✆ Here is working example of struct function: ✞ 1 #include <stdio.h> 3 struct student { int id; 5 char *name ; float perc ; 7 } st , st1 , st2; 9 int main () { st.id = 1; 11 st1.name = "Arun Umrao"; st2.perc = 90.5; 13 printf("Id is: %d n", st.id); printf("Name is: %s n", st1.name ); 15 printf("Percentage is: %f n", st2.perc ); return 0; 17 } ✌ ✆ ✞ Id is: 1 Name is: Arun Umrao Percentage is: 90.500000 ✌ ✆ Another simple example is given below. ✞ 1 #include <stdio.h> 3 struct data {
  • 7. 406 File & Data Structure int val; 5 float b; }; 7 int main (void ) { 9 struct data s; s.val = 12; 11 s.b = 3.14159; printf("The val field in s is: %dn", s.val); 13 return 0; } ✌ ✆ ✞ The val field in s is: 12 ✌ ✆ Pointer can be also used in structure. An instance of a structure ‘data’ using a pointer is declared as ✞ 1 data *<variable >; ✌ ✆ Member values of the structure declared with pointer are initialized or accessed by using operator −> (indirect member access). See the following syntax, in which a structure ‘Func’ is declared by using a pointer and its member values are set by using operator − >. ✞ 1 struct Func { int val; 3 float fl; }; 5 struct Func *b; b->val = 3491; ✌ ✆ st st++ val fl A working example is ✞ #include <stdio.h> 2 struct Func { 4 int val; float fl; 6 }; 8 int main (void ) { /* Func struct required for pointer */ 10 struct Func a; /* this is a pointer to a struct Func */
  • 8. 3.3. DATA STRUCTURES 407 12 struct Func *b; b->val = 3491; 14 printf("The value of b is %d.", b->val); return 0; 16 } ✌ ✆ ✞ The value of b is 3491. ✌ ✆ A struct data can also be passed to a function by using address of procedure. See the example below in which data struct is passed to function ‘Plantation’. ✞ 1 #include <stdio.h> 3 /* Data structure */ struct Data { 5 int Trees; int Plants; 7 }; 9 /* function Plantation with data structure as pointer */ void Plantation (struct Data *f) { 11 f->Trees = 10; f->Plants = 20; 13 } 15 int main (void ) { /* Struct data structure */ 17 struct Data Bio; /* Pass address ‘Bio ’ into struct ‘Data ’ as pointer */ 19 Plantation (& Bio); printf("Trees : %dn", Bio.Trees); /* prints "10" */ 21 printf("Plants : %dn", Bio.Plants); /* prints "20" */ return 0; 23 } ✌ ✆ ✞ Trees : 10 Plants : 20 ✌ ✆ A constant pointer, once holds an address cannot change to the new address. It means a constant pointer, if already pointing to an address, cannot point to a new address. ✞ #include <stdio.h> 2 int main (void ) { 4 char ch = ’A’; char cH = ’B’; 6 char * const ptr = &ch; // A constant pointer 8 ptr = &cH; // Illegal way of pointer .
  • 9. 408 File & Data Structure 10 return 0; } ✌ ✆ In case of pointer to structure, if the things on the left of the ‘.’ (dot) or ‘−>’ operator is qualified (with const or volatile) then the result is also has those qualifiers associated with it. In the following example, when the pointer points to a qualified type the result got is also qualified. ✞ 1 #include <stdio.h> #include <stdlib.h> 3 struct myStruct { 5 int i; }; 7 main () { 9 /* Initialisation of structures . */ struct myStruct *Ptr , s_item; 11 /* Initialisation of structures of constant qualifier . */ const struct myStruct *s_Ptr; 13 /* Set the item value.*/ s_item.i = 1; /* OK */ 15 /* Assigning new pointer .*/ Ptr = &s_item; 17 Ptr ->i += 2; /* OK */ /* Constant qualified pointer.*/ 19 s_Ptr = &s_item; s_Ptr ->i = 0; /* Not OK as points to constant type qualifier . */ 21 exit ( EXIT_SUCCESS ); 23 } ✌ ✆ A structure can also be initialized at the starting of program if structure is defined as ✞ 1 struct employee { int no; 3 int sex; int age; 5 }; struct employee EmpNo={<int >, <int >, <int >}; ✌ ✆ The following example clears the initialization of the structure. ✞ #include <stdio.h> 2 struct employee { 4 int no; int sex; 6 int age; }; 8
  • 10. 3.3. DATA STRUCTURES 409 int main () { 10 /* Structure declared and initialized .*/ struct employee EmpNo ={10 ,1 ,15}; 12 printf("%dt%dt%dn", EmpNo.no , EmpNo.sex , EmpNo.age); return 0; 14 } ✌ ✆ A self referential structures has same member name as its name is. See the following example. ✞ struct myStruct { 2 int i; char j[10]; 4 struct myStruct *myStructRef ;// Legal }; ✌ ✆ In case of pointer type self referral, size of a pointer to a structure is known to compiler even before the size of the structure has been determined. Note that the self referential structure should be a pointer not a structure. For example, at above structure, ‘myS- tructRef’ is pointer not a structure itself. If it is a structure, then it will contain member ‘myStructRef’ recursively (member within member). ✞ 1 struct myStruct { int i; 3 char j[10]; struct myStruct myStructRef ; // Illegal 5 }; ✌ ✆ Following type of self referral is also illegal. ✞ 1 typedef struct { int i; 3 char j[10]; myStructAlias *myStructRef ; // Illegal 5 } myStructAlias ; ✌ ✆ The reason is that the type name is defined after the declaration of structure, therefore, line ✞ 1 struct myStruct *myStructRef ; // Illegal ✌ ✆ will show error as self referral structure is declared before the type name is defined. The legal form is given below: ✞ 1 typedef struct myStruct { int i; 3 char j[10]; struct myStruct *myStructRef ; // Legal 5 } myStructAlias ; ✌ ✆
  • 11. 410 File & Data Structure Nested Structure Structure within structure i.e. nested structure can also be declared by using either normal variable or pointer. In following example, a nested structure is declared and declared by simple variable. From structural inheritance, inner structure is accessible from instances of outer structure. ✞ 1 #include <stdio.h> 3 int main () { 5 /* date structure */ struct date { 7 int day; int month; 9 int year ; }; 11 /* variety structure */ 13 struct variety {/* Upper level structure */ char *name ; 15 /* Date is Lower level nested structure . it is * 17 * declared as normal structure . Elements of * * date structure are accessed by dot (.). */ 19 struct date date ; } tr; /* Structure declared as normal variable . * 21 * Elements can be accessed by (.) symbol.*/ 23 /* Accessing structure elements by using synopsis like * up_level_struct (.) up_level_elem 25 * or * up_level_struct (.) low_level_struct (.) low_level_elem */ 27 tr.name = "A"; tr.date .day = 10; 29 printf("Name : %sn", tr.name ); printf("day : %dn", tr.date .day); 31 return 0; } ✌ ✆ ✞ Name : A day : 10 ✌ ✆ In simple variable type declaration of structure, elements are accesses by using dot (.). Using of pointer symbol (−>) throws the errors. ✞ #include <stdio.h> 2 int main () { 4 /* date structure */
  • 12. 3.3. DATA STRUCTURES 411 6 struct date { int day; 8 int month; int year ; 10 }; 12 /* variety structure */ struct variety {/* Upper level structure */ 14 char *name ; 16 /* Date is Lower level nested structure . it is * * declared as normal structure . Elements of * 18 * date structure are accessed by dot (.). */ struct date date ; 20 } tr; /* Structure declared as normal variable . * * Elements can be accessed by (.) symbol.*/ 22 /* Accessing structure elements by using synopsis like 24 * up_level_struct (.) up_level_elem * or 26 * up_level_struct (.) low_level_struct (.) low_level_elem */ tr.name = "A"; 28 tr.date .day = 10; 30 /* Following line show errors. Reason is that we are trying* *to access the element by pointer symbol (->) even though* 32 *the structure ‘tr ’ is declared here as normal variable . */ tr ->date .month = 11; 34 printf("Name : %sn", tr.name ); printf("day : %dn", tr.date .day); 36 return 0; } ✌ ✆ Other-way to assign a structure inside another struct is pointer method. In pointer method, elements are accessed by using pointer symbol (−>) and dot (.). ✞ 1 #include <stdio.h> 3 int main () { 5 /* date structure */ struct date { 7 int day; int month; 9 int year ; }; 11 /* variety structure */ 13 struct variety {/* Upper level structure */ char *name ; 15
  • 13. 412 File & Data Structure /* Date is Lower level nested structure . it is * 17 * declared as normal structure . Elements of * * date structure are accessed by dot (.). */ 19 struct date date ; } *tr; /* Structure declared as pointer variable . * 21 * Elements can be accessed by (->) symbol.*/ 23 /* Accessing structure elements by using synopsis like * up_level_struct (->) up_level_elem 25 * or * up_level_struct (->) low_level_struct (.) low_level_elem */ 27 tr ->name = "A"; tr ->date .day = 10; 29 printf("Name : %sn", tr ->name ); printf("day : %dn", tr ->date .day); 31 return 0; } ✌ ✆ ✞ Name : A day : 10 ✌ ✆ Again, indirect membership operator or structure pointer operator (−>) is not used in the level or element of the structure declared as normal variable. ✞ #include <stdio.h> 2 int main () { 4 /* date structure */ 6 struct date { int day; 8 int month; int year ; 10 }; 12 /* variety structure */ struct variety {/* upper level structure */ 14 char *name ; 16 /* Date is Lower level nested structure . it is * * declared as normal structure . Elements of * 18 * date structure are accessed by dot (.). */ struct date date ; 20 } *tr; /* Structure declared as pointer variable .* * Elements are accessed by (->) symbol. */ 22 /* Following lines show errors. We are trying * 24 *to access the elements of structure ‘date ’ * *by pointer symbol (->) while the structure * 26 *‘date ’ is declared here as normal variable .*/ tr ->date ->day = 10;
  • 14. 3.3. DATA STRUCTURES 413 28 tr.date ->day = 10; return 0; 30 } ✌ ✆ But the lower level elements can also be accessed by using pointer symbol (−>) if lower level structure is also declared as pointer level. ✞ #include <stdio.h> 2 int main () { 4 /* date structure */ 6 struct date { int day; 8 int month; int year ; 10 }; 12 /* variety structure */ struct variety {/* upper level structure */ 14 char *name ; /* Date is Lower level nested structure . it is * 16 * declared as pointer structure . Elements of * * date structure are accessed by dot (->). */ 18 struct date *date ; } *tr; /* Structure declared as pointer variable . * 20 * Elements can be accessed by (->) symbol.*/ 22 /* Accessing structure elements by using synopsis like * up_level_struct (->) up_level_elem 24 * or * up_level_struct (->) low_level_struct (->) low_level_elem */ 26 tr ->date ->day = 10; tr ->date ->month = 10; 28 printf("Day : %dn", tr ->date ->day); printf("Month : %dn", tr ->date -> month); 30 return 0; } ✌ ✆ ✞ Day : 10 Month : 10 ✌ ✆ In above examples, it is clarified that, elements of structures declared as variable type are accessed by using dot (.) and elements of structure declared as pointer type are accessed by using indirect membership operator or structure pointer operator (−>). ✞ #include <stdio.h> 2 int main () { 4
  • 15. 414 File & Data Structure /* date structure */ 6 struct date { int day; 8 int month; int year ; 10 }; 12 /* variety structure */ struct variety {/* up_level_struct (uls)*/ 14 char *name ; 16 /* Date is Lower level nested structure . it is * * declared as pointer structure . Elements of * 18 * date structure are accessed by dot (->). */ struct date *date ; 20 } tr; /* Structure declared as normal variable .* * Elements can be accessed by dot (.). */ 22 /* Accessing structure elements by using synopsis like 24 * up_level_struct (.) up_level_elem * or 26 * up_level_struct (.) low_level_struct (->) low_level_elem */ tr.date ->day = 10; 28 tr.date ->month = 10; printf("Day : %dn", tr.date ->day); 30 printf("Month : %dn", tr.date -> month); return 0; 32 } ✌ ✆ ✞ Day : 10 Month : 10 ✌ ✆ Structure As Arguments Like other variables, file pointers and function pointers, a structure can also be passed to a function as its argument. The method of passing a structure to a function is given below: ✞ int myFunc(struct <structure name > <local var >); ✌ ✆ In the following example, structure ‘g len’ is passed to function ‘sum’. Numerical values of structure elements are get summed and returned to the caller. shown in the example below: ✞ 1 #include <stdio.h> #define TREE_NUM 50 3 /* Structure for garden tree length.*/ 5 struct g_len {
  • 16. 3.3. DATA STRUCTURES 415 char gardens[TREE_NUM ]; 7 double t_len_1; double t_len_2; 9 }; 11 /* Structure passed to the function .*/ double sum(struct g_len val) { 13 return (val.t_len_1 + val.t_len_2 ); } 15 int main (void ) { 17 /* Initialized the structure .*/ struct g_len sbi = { 19 "G DELHI", 6524.12 , 21 9458.87 }; 23 printf("Tree length is %.2fm.n", sum(sbi)); return 0; 25 } ✌ ✆ ✞ Tree length is 15982.99 m. ✌ ✆ Structure data allows us to write data of desired size into text or binary file. To write struct data into a file we use fwrite function as ✞ 1 FILE *fp; /*A file stream */ struct TreeData { /* Structure TreeData */ 3 int x; int y; 5 } /* Create TreeData space.*/ 7 struct TreeData *td = malloc(sizeof ( struct TreeData )); /* Write structure data into file .*/ 9 fwrite(td , sizeof (struct TreeData ), 1, fp); ✌ ✆ Here is complete example: ✞ 1 #include <stdio.h> 3 struct TreeData { int x_old; 5 int y_old; int x_new; 7 int y_new; int val; 9 }; 11 void insert(char *f, int x_old , int y_old , int val) { struct TreeData *td = malloc(sizeof (struct TreeData )); 13 FILE *fp;
  • 17. 416 File & Data Structure int xnew ; 15 int ynew ; if (td ->x_new == 0 || td ->y_new == 0) { 17 td ->x_new = 0; td ->y_new = 0; 19 } else { xnew = td ->x_new; 21 ynew = td ->y_new; } 23 td ->x_old = x_old; td ->y_old = y_old; 25 td ->val = val; fp = fopen(f, "wb"); 27 fwrite(td , sizeof ( struct TreeData ), 1, fp); fclose(fp); 29 td ->x_new = xnew + 1; td ->y_new = ynew + 1; 31 } 33 int main () { char *f = "TreeNode .txt"; 35 struct TreeData myNode; insert(f, 0, 0, 95); 37 return 0; } ✌ ✆ Multi-Dimensional Struct Technically a multidimensional structure can not be declared. But tricking methods can be used to store a multidimensional data with help of structure. For example, a two dimensional values can be stored via structure if we declared a structure with two elements. One for storing data of one dimension and other for storing data of second dimension. Yet a structure can be declared as an array. A structure capable of storing two dimensional data is declared as given below: ✞ struct myStruct { /* Structure with 2 elements */ 2 int i; /* First element of 4 bytes size */ int j; /* Second element of 4 bytes size */ 4 }; struct myStruct s[2]; /* Initialize 2-dim structure for * 6 *storing two elements of an array*/ ✌ ✆ The memory size required to store this structure is equal to the product of number of dimension of structure and total size of structure elements. In above syntax, size of structure is (4 + 4) × 2 = 16 bytes. See the example below: ✞ #include <stdio.h> 2 int main () { 4
  • 18. 3.3. DATA STRUCTURES 417 struct twoDimStruct { 6 int x; int y; 8 }; struct twoDimStruct s[10]; 10 printf("Size of Structure is %d bytes.n", sizeof (s)); return 0; 12 } ✌ ✆ ✞ Size of Structure is 80 bytes. ✌ ✆ Here, structure creates space for data storage, hence memory allocation is not required. But we can use dynamically allocated memory as shown below: ✞ 1 #include <stdio.h> 3 int main () { int i; 5 typedef struct { 7 int x; int y; 9 } mStruc; /* Allocate memory space for all * 11 *columns of size (4+4) *10 bytes.*/ mStruc **s = (mStruc **) malloc (10 * sizeof (mStruc *)); 13 for (i = 0; i < 10; i++) { /* Allocate memory space for each * 15 *rows as group of above columns .*/ s[i] = (mStruc *) malloc (10 * sizeof (mStruc)); 17 } return 0; 19 } ✌ ✆ Assume a four element structure as syntaxed below: ✞ 1 typedef struct { int x; /*4 bytes long */ 3 char c; /*1 byte long */ int y; /*4 bytes long */ 5 char k; /*1 byte long */ } e; 7 /* **s points to memory for 10 elements * * where each element is 10 bytes long .* 9 * it forms columns of the each row. */ e **s = (e **) malloc (10 * sizeof (e *)); 11 for (i = 0; i < 10; i++) { /* Allocate memory space for each * 13 *rows as group of above columns .*/ s[i] = (e *) malloc (10 * sizeof (e)); 15 } ✌ ✆
  • 19. 418 File & Data Structure The memory space is created for a structure array of 10 × 10. The memory space is reserved with help of malloc command. The memory space is represented by: n n n n x c c n n n n y c k e[0] ∗∗ s n n n n x c c n n n n y c k e[1] s[0] We can store value for each structure and retrieve it as and when required. See the example below: ✞ 1 #include <stdio.h> 3 int main () { 5 struct twoDimStruct { int x; 7 int y; }; 9 struct twoDimStruct s[10]; s[1]. x = 5; 11 s[1]. y = 10; s[3]. y = 25; 13 printf("s[1]. x = %d.n", s[1]. x); printf("s[1]. y = %d.n", s[1]. y); 15 printf("s[3]. x = %d.n", s[3]. x); printf("s[3]. y = %d.n", s[3]. y); 17 return 0; } ✌ ✆ ✞ s[1]. x = 5. s[1]. y = 10. s[3]. x = 1. s[3]. y = 25. ✌ ✆ When structure is declared as array, if reserves memory equal to the product of size of structure and structure array size. For example, the statement ✞ struct twoDimStruct s[10]; ✌ ✆ memory space for ten struct elements are reserved. Total size of instance ‘s’ is (4+4)×10 = 80 bytes. If structure is declared as ✞ 1 struct twoDimStruct s[10][3]; ✌ ✆ then it has ten rows and three columns in which each element has structure elements ‘x’ and ‘y’. See the example given below:
  • 20. 3.3. DATA STRUCTURES 419 ✞ 1 #include <stdio.h> 3 int main () { 5 struct twoDimStruct { int x; 7 int y; }; 9 struct twoDimStruct s[4][3]; s[1][0]. x = 5; 11 s[1][0]. y = 6; s[1][1]. x = 7; 13 s[1][1]. y = 8; s[1][2]. x = 9; 15 s[1][2]. y = 10; printf("%dt%dt", s[1][0].x, s[1][0]. y); 17 printf("%dt%dt", s[1][1].x, s[1][1]. y); printf("%dt%dn", s[1][2].x, s[1][2]. y); 19 return 0; } ✌ ✆ ✞ 5 6 7 8 9 10 ✌ ✆ The memory arrangement of the two dimensional structure is shown in the following figure. x00 x01 x02 y00 y01 y02 x10 x11 x12 y10 y11 y12 x20 x21 x22 y20 y21 y22 x30 x31 x32 y30 y31 y32 The address of the structure elements are retrieved in the following example to check the order of elements in the memory. ✞ 1 #include <stdio.h> 3 int main () { 5 struct twoDimStruct { int x; 7 int y; }; 9 struct twoDimStruct s[4][3]; s[1][0]. x = 5; 11 s[1][0]. y = 6; s[1][1]. x = 7;
  • 21. 420 File & Data Structure 13 s[1][1]. y = 8; s[1][2]. x = 9; 15 s[1][2]. y = 10; printf("%xt%xn", &(s[1][0].x), &(s[1][0].y)); 17 printf("%xt%xn", &(s[1][1].x), &(s[1][1].y)); printf("%xt%xn", &(s[1][2].x), &(s[1][2].y)); 19 return 0; } ✌ ✆ ✞ c280b9b8 c280b9bc c280b9c0 c280b9c4 c280b9c8 c280b9cc ✌ ✆ A structure can be returned from a function but an array can not be so. See the following example, in which a copy of the local, automatically allocated structure is made on return and then the local copy is destroyed. ✞ 1 #include <stdio.h> 3 typedef struct { double square , cube ; 5 } A; 7 A getAns( double in) { A out = { 9 . square = in*in , .cube = in * in * in 11 }; return out; 13 } 15 int main () { A res = getAns (3); 17 printf("Result: %gt%gtn", res.square , res.cube ); return 0; 19 } ✌ ✆ ✞ Result: 9 27 ✌ ✆ Return Structure from Function We may return structure from inside of a function. Note that the address of returned structure is address of first member of the structure. Value of first member of structure is printed in output console with warning. If there are multiple members in a structure then it is good practice to call member of the structure rather than calling whole structure. See the example below: ✞ 1 #include <stdio.h>
  • 22. 3.3. DATA STRUCTURES 421 3 struct st { int i; /* First element */ 5 int j; /* Second element */ }; 7 struct st myF(int x) { 9 struct st s; /* Create structure object*/ s.i = x; /* Set value to first element */ 11 s.j = 2 * x; /* Set value to second element */ return s; /* Return structure address */ 13 } 15 int main () { 17 /* Prints first element of the structure */ printf("%dn",myF (20) .i); 19 /* Prints second element of the structure */ printf("%dn",myF (20) .j); 21 return 0; } ✌ ✆ ✞ 20 40 ✌ ✆ 3.3.2 Enumerate In C, enumerations are created by explicit definitions, which use the enum keyword and are reminiscent of struct and union definitions. See example below. ✞ #include <stdio.h> 2 enum { 4 /*0*/ /*1*/ /*2*/ TRUE , FALSE , NO 6 } b = NO; 8 int main (int argc , char ** argv ) { printf("bool : %dn", b); 10 return 0; 12 } ✌ ✆ ✞ bool : 2 ✌ ✆ C also allows the programmer to choose the values of the enumeration constants explicitly, even without type.
  • 23. 422 File & Data Structure ✞ 1 #include <stdio.h> 3 enum { TRUE = 0, FALSE = 1, NO = 10 5 } b = NO; 7 int main (int argc , char ** argv ) { printf("bool : %dn", b); 9 return 0; 11 } ✌ ✆ ✞ bool : 10 ✌ ✆ In enumerate the values are assigned successively. If any enum key is set to a specific value then next enum key has value one larger than its preceding enum key. ✞ 1 #include <stdio.h> 3 int main () { 5 enum COLORS { BLUE , /* Index value 0*/ 7 GREEN = 3, /* Index value 3*/ YELLOW , /* Index value 4*/ 9 RED = 2, /* Index value 2*/ BLACK /* Index value 3*/ 11 }; printf("The colors are:n"); 13 printf("%dn", BLUE );/*0*/ printf("%dn", YELLOW);/*4*/ 15 printf("%dn", BLACK);/*3*/ return 0; 17 } ✌ ✆ ✞ The colors are: 0 4 3 ✌ ✆ 3.3.3 Unions The definition of a union is similar to that of a struct. The difference between the two is that in a struct, the members occupy different areas of memory, but in a union, the members occupy the same area of memory. Thus, in the following type, for example: ✞ union { 2 char c;
  • 24. 3.3. DATA STRUCTURES 423 int d; 4 } u; ✌ ✆ The programmer can access either ‘u.c’ or ‘u.d’, but not both at the same time. In the following example, we modify only value of member ‘c’ and access it, we get the correct result. ✞ #include <stdio.h> 2 #include <string.h> 4 union Data { char c; 6 int d; }; 8 int main () { 10 union Data data ; 12 data .c = 10; 14 printf("data .c : %dn", data .c); 16 return 0; } ✌ ✆ ✞ data .c : 10 ✌ ✆ data.c 0000 1010 In the following example, we modify values of members ‘c’ and ‘d’ and access it, we get the incorrect result as ‘data.c’ and ‘data.d’ uses same memory space and ‘data.d’ overwrite and modified the value of ‘data.c’ as well. Thus we get undesirable value of ‘data.c’ but correct value of ‘data.d’. ✞ 1 #include <stdio.h> #include <string.h> 3 union Data { 5 char c; int d; 7 }; 9 int main () { union Data data ; 11
  • 25. 424 File & Data Structure data .c = ’C’; 13 data .d = 201170739; 15 /*|<--------------data .d--------------->|* * 00001011 11111101 10011111 00110011 * 17 * |<-data .c->|*/ 19 printf("data .c : %cn", data .c); printf("data .d : %dn", data .d); 21 return 0; 23 } ✌ ✆ ✞ data .c : 3 data .d : 201170739 ✌ ✆ data.d data.c 0000 1011 1111 1101 1001 1111 0011 0011 Since ‘data.c’ and ‘data.d’ occupy the same area of memory, so, modifying the value of one member of union modifies the values of the other members, sometimes in unpredictable ways. The size of a union is the size of its largest member. Another simple example is given again. ✞ #include <stdio.h> 2 #include <string.h> 4 union Data { char c; 6 int d; char str [15]; 8 }; 10 int main () { union Data data ; 12 /* update shared memory as char */ data .c = ’C’; 14 /* update shared memory as integer */ data .d = 201170739; 16 /* update shared memory as string */ strcpy(data .str , "C Programming "); 18 /* Read last updates as character */
  • 26. 3.3. DATA STRUCTURES 425 20 printf("data .c : %cn", data .c); /* Read last updates as integer */ 22 printf("data .d : %dn", data .d); /* Read last updates as string*/ 24 printf("data .str : %sn", data .str); 26 return 0; } ✌ ✆ ✞ data .c : C data .d : 1917853763 data .str : C Programming ✌ ✆ union is used as shared structure in which shared memory is updated or accessed for last value of any data type. Each element of the union structure reads/updates shared memory bytes in same data type as it is declared in the union. 3.3.4 Stack A stack is a particular kind of abstract data type or collection in which the principal (or only) operations on the collection are the addition of an entity to the collection, known as “push” and removal of an entity, known as “pop”. The relation between the push and pop operations is such that the stack is a Last-In-First-Out (LIFO) data structure. In most high level languages, a stack can be easily implemented either through an array or a linked list. A stack needs to elements, one stack counter and second stack memory. Stack memory either holds memory address of data located at the address (i.e. string stack) or holds actual numeric values (integer stack). Stack pointer/counter controls to how many elements may be pushed into a stack. It prevents pushing of an element in the memory location that is not part of the stack. For example see following code which has declared an array of 4 integers (i.e. stack size is four) and memory is allocated to store these 4 integer values. ✞ 1 int *myA; myA = malloc (4*4); ✌ ✆ Here, 16 bytes are reserved to hold 4 integer values. If we try to add 5th element into this array, the array parameter reached beyond the allocated memory. It is violation of shared memory. Stack will graphically represent as given below: myA Stack (0 to 3) Low count High count Here, pointer ‘myA’ should never be pushed beyond the range of 16 bytes. Initially, ‘myA’ is at the root of the stack, i.e. at the index 0. Now, push an integer into the stack.
  • 27. 426 File & Data Structure ✞ *myA =10; ✌ ✆ Integer 10 is stored in the current memory location of ‘myA’. It is caller’s responsibility to increase the pointer otherwise the next push shall put the new value in same location and old value shall be overwritten by new value. The pointer location is incremented one by ✞ 1 myA ++; ✌ ✆ Now, stack shall be looked like 10 myA Stack (0 to 3) Low count High count By incrementing/decrementing the pointer within the memory allocated range, we can either push a value into the stack or may popped a value from the stack. A sudden jump of pointer within memory location is also permitted. ✞ 1 myA +3; *myA =50; ✌ ✆ Now, stack shall be looked like 10 50 myA Stack (0 to 3) Low count High count Note that, one integer is four bytes long, therefore, ‘myA+3’ shall make a jump of 12 bytes to the pointer ‘myA’. Stack may be declared as pointer or as an array. ✞ int myA [4]; /* Declaration & memory allocation */ 2 /* Other method */ int *myA; /* Declaration */ 4 myA = malloc (4*4); /* Memory allocation */ ✌ ✆ Location of stack elements may be accessed by indexing or by dereferencing the array. If stack is considered as a pointer then it is accessed as explained above. If it is considered as an array then stack shall be looked like as given below and its elements can be accessed by indexing them.
  • 28. 3.3. DATA STRUCTURES 427 myA[0] myA[1] myA[2] myA[3] Stack (0 to 3) Low count High count In computer, index counting starts from 0 to infinity. Push A Value Pushing a value to a stack means adding an element into the stack. A value is pushed at the current location of the pointer of stack counter (in case of array). Counter, some time is used as index value. For example, in array type stack, 2nd element is pushed at index 1 of ‘myA’. ✞ myA [1] = 20; ✌ ✆ 20 myA[1] Stack (0 to 3) Low count High count If counter or index of array is incremented by more than one, then it is also called pushing of element as the location of stack pointer is changed and new element shall be pushed here. 20 myA[3] Stack (0 to 3) Low count High count Pop A Value Normally, system retrieves value from the current location of pointer or index counter. Therefore, popping does not mean that value at particular location is chagned to null before the changing the location of pointer or counter. If counter/index/pointer is decre- mented by two without retrieving the values, then it is also said popping of elements even though the values are intact at their memory locations. 10 20 30 40 myA[3] Stack (0 to 3) Low count High count
  • 29. 428 File & Data Structure Assume that, initially pointer is at location ‘myA[3]’ and it is decremented by two locations, then we say that 3rd and 4th elements are popped. 10 20 30 40 myA[1] Stack (0 to 3) Low count High count Now, the pointer/counter is pointing to 2nd element of the stack. Adding of new element will change the value at this memory location and retrieval may allow utilization of the value stored at this location. Actually, it is user’s responsibility to control the position of pointer or index within the stack. Array in Stack The array implementation aims to create an array where the first element (usually at the zero-offset) is at the bottom. I.e., array[0] is the first element pushed onto the stack and the last element popped off. The program must keep track of the size or the length of the stack. ✞ 1 data type struct { size_t size ; // element counter 3 int items[STACKSIZE ]; // stack memory } STACK; ✌ ✆ The push() operation is used both to initialize the stack, and to store values into it. It is responsible for inserting (copying) the value in array and for incremental the element counter. Note that, when an element is pushed into the stack, counter should be increased by one and when one element is removed from the stack, counter should be decreased by one. It is also need to check that the array is not completely full or completely empty. ✞ void push (STACK *ps , int x) { 2 if (ps ->size == STACKSIZE ) { fputs("Error: stack overflow n", stderr); 4 abort(); } else 6 ps ->items[ps ->size ++] = x; } ✌ ✆ The pop() operation is responsible for removing a value from the stack, and decremented the value of array. It is also need to check that the array is not already empty. Popping of an element from the stack, decreases the counter by one. ✞ 1 int pop(STACK *ps) { if (ps ->size == 0) { 3 fputs("Error: stack underflow n", stderr); abort(); 5 } else
  • 30. 3.3. DATA STRUCTURES 429 return ps ->items[--ps ->size ]; 7 } ✌ ✆ Following is the simple example that explains the stack in array by using struct structure method. ✞ 1 #include <stdio.h> 3 #define MAXSIZE 5 5 struct stack /* Structure definition for stack */ { int stk[MAXSIZE ]; 7 int top; }; 9 struct stack s; 11 /* Function declaration /Prototype */ 13 void push (void ); 15 int pop(void ); void display (void ); 17 void main () { 19 int choice; int option = 1; 21 s.top = -1; 23 printf("STACK OPERATION n"); 25 while (option) { printf(" --------------------n"); 27 printf(" 1 --> PUSH n"); printf(" 2 --> POP n"); 29 printf(" 3 --> DISPLAY n"); printf(" 4 --> EXIT n"); 31 printf(" --------------------n"); 33 printf("Enter your choice : n"); scanf("%d", &choice); 35 switch (choice) { 37 case 1: push (); 39 break; case 2: 41 pop(); break; 43 case 3: display (); 45 break;
  • 31. 430 File & Data Structure case 4: 47 return; } 49 fflush(stdin); 51 printf("Do you want to continue (Type 0 or 1)?n"); scanf("%d", &option); 53 } } 55 /* Function to add an element to the stack*/ 57 void push () { int num; 59 if (s.top == (MAXSIZE - 1)) { printf("Stack is Full n"); 61 return; } else { 63 printf("Enter a valuen"); scanf("%d", &num); 65 s.top = s.top + 1; s.stk[s.top] = num; 67 } return; 69 } 71 /* Function to delete an element from the stack*/ int pop() { 73 int num; if (s.top == -1) { 75 printf("Stack is Emptyn"); return (s.top); 77 } else { num = s.stk[s.top ]; 79 printf("poped element is = %dn", s.stk[s.top]); s.top = s.top - 1; 81 } return (num); 83 } 85 /* Function to display the status of the stack*/ void display () { 87 int i; if (s.top == -1) { 89 printf("Stack is emptyn"); return; 91 } else { printf("nThe status of the stack isn"); 93 for (i = s.top; i >= 0; i--) { printf("%dn", s.stk[i]); 95 } }
  • 32. 3.3. DATA STRUCTURES 431 97 printf("n"); } ✌ ✆ First screen of the program output is ✞ -------------------- 1 --> PUSH 2 --> POP 3 --> DISPLAY 4 --> EXIT -------------------- Enter your choice : ✌ ✆ String in Stack String can be stored as stack. To store string in stack, a stack variable of character type is initialized. Generally, this stack variable is a two dimensional array, in which first dimension represents the row number and second dimension represents to string size. For example, a string stack of size 10, having largest string size of 20 characters is declared as ✞ 1 char myStack [10][20]; ✌ ✆ Here, stack size is 10 and we can put the string of length upto 20 characters. 3.3.5 Classes In C, we can not declared function element inside the structure. This is why, it is hard to call a function as object. Object oriented programming in C is restricted within scope of the structure. There are four steps to be followed to create a function as object. The steps involved, (i) create a class, (ii) deleted a class, (iii) update the class and (iv) access the class. Create Class Here, using struct keyword, a class ‘myClass’ is declared. It has an element ‘variable’ of int data type. The class is initialized to set the value of the class element ‘variable’ to 0. ✞ 1 typedef struct myClass { int variable ; 3 } *MyClass ; 5 MyClass myNewClass () { MyClass this = malloc(sizeof *this ); 7 this -> variable = 0; return this ; 9 } ✌ ✆
  • 33. 432 File & Data Structure Delete Class As each class when declared and called, a memory space is reserved to store data in ‘variable’. After execution of object function, the memory allocated, must be freed by using free() function. ✞ 1 void myNewClassDelete (MyClass * this ) { if (this ) { 3 free (* this ); *this = NULL ; 5 } } ✌ ✆ Update Class This function class updates the data of ‘variable’ according to the rules set by statements and expressions inside this function. ✞ void myNewClassSet (MyClass this ) { 2 this -> variable = 1; } ✌ ✆ Access Class It is main part of the program, from where we can access the object function. Result is printed in output console by printf function. ✞ 1 int main () { MyClass obj = myNewClass (); 3 myNewClassSet (obj); printf("%d", obj ->variable ); 5 myNewClassDelete (& obj); return 0; 7 } ✌ ✆ Complete example using above four steps is given below: ✞ 1 #include <stdlib.h> #include <stdio.h> 3 typedef struct myClass { 5 int variable ; } *MyClass ; 7 MyClass myNewClass () { 9 MyClass this = malloc(sizeof *this ); this -> variable = 0; 11 return this ; } 13
  • 34. 3.3. DATA STRUCTURES 433 void myNewClassDelete (MyClass * this ) { 15 if (this ) { free (* this ); 17 *this = NULL ; } 19 } 21 void myNewClassSet (MyClass this ) { this -> variable = 1; 23 } 25 int main () { MyClass obj = myNewClass (); 27 myNewClassSet (obj); printf("%d", obj ->variable ); 29 myNewClassDelete (& obj); return 0; 31 } ✌ ✆ 3.3.6 Link List Linked List (Array) Arrays and linked list are linear data structure. In array, elements are stored in sequential memory locations, while in linked list, elements are linked using pointers. Linked lists are preferred over arrays as array has fixed size and insertion of element in between the array elements is expensive. 11 0×042a 0×1225 34 0×1225 0×a22c 56 0×a22c 0×a2cc myP NULL Linked lists have some drawbacks too. (i) Random access is not allowed. and (ii) extra memory space for a nextPtr is required with each element of the list. A linked list node is created as given below: ✞ 1 struct list_Elem { int data ; 3 struct list_Elem *nextElemPtr ; }; ✌ ✆ In this prototype, element of structure is structure itself. It is forbidden in the structure definition. But in fact it only contains a nextPtr to itself. It is allowed as by the time the compiler reaches the nextPtr declaration it already knows that there is such a thing as a ‘struct list Elem’ so the declaration is permitted. In fact, it is possible to make a incomplete declaration of a structure by saying
  • 35. 434 File & Data Structure ✞ struct list_Elem ; ✌ ✆ at some point before the full declaration. This will allow the declaration of pointers before the full declaration is seen. It is also important in the case of cross-referencing structures where each must contain a nextPtr to the other, as shown in the following example. ✞ 1 struct s_1; /* Incomplete type */ 3 struct s_2 { int something ; 5 struct s_1 *sp; }; 7 struct s_1 { /* Full declaration */ 9 float something ; struct s_2 *sp; 11 }; ✌ ✆ This illustrates the need for incomplete types. It also illustrates an important thing about the names of structure members: they inhabit a name-space per structure, so element names can be the same in different structures without causing any problems. Incomplete types may only be used where the size of the structure isn’t needed yet. A full declaration must have been given by the time that the size is used. The later full declaration mustn’t be in an inner block because then it becomes a new declaration of a different structure. ✞ 1 struct x; /* Incomplete type */ 3 /* valid uses of the tag */ struct x *p, func (void ); 5 void f1(void ) { 7 struct x { int i; 9 }; /* redeclaration ! */ } 11 /* full declaration now */ 13 struct x { float f; 15 } s_x; 17 void f2(void ) { /* valid statements */ 19 p = &s_x; *p = func (); 21 s_x = func (); } 23 struct x func (void ) { 25 struct x tmp;
  • 36. 3.3. DATA STRUCTURES 435 tmp.f = 0; 27 return (tmp); } ✌ ✆ The other principal way to get incomplete types is to declare arrays without specifying their size, their type is incomplete until a later declaration provides the missing informa- tion: ✞ int ar[ ]; /* incomplete type */ 2 int ar [5]; /* complete type */ ✌ ✆ If you try that out, it will only work if the declarations are outside any blocks (external declarations), but that’s for other reasons. There were three elements linked into the list, which could have been built like this: ✞ struct list_Elem { 2 int data ; struct list_Elem *nextPtr ; 4 } ar [3]; 6 main () { ar [0]. data = 5; /* Add data to first element */ 8 ar [0]. nextPtr = &ar [1]; /* Add address of second element */ ar [1]. data = 99; /* Add data to second element */ 10 ar [1]. nextPtr = &ar [2]; /* Add address of third element */ ar [2]. data = -7; /* Add data to third element */ 12 ar [2]. nextPtr = 0; /* mark end of list */ return (0); 14 } ✌ ✆ and the contents of the list can be printed in two ways. The array can be traversed in order of index, or the pointers can be used as shown in the following example. ✞ #include <stdio.h> 2 #include <stdlib.h> 4 struct list_Elem { int data ; 6 struct list_Elem *nextPtr ; } ar [3]; 8 main () { 10 struct list_Elem *lp; 12 ar [0]. data = 5; /* Add data to first element */ 14 ar [0]. nextPtr = &ar [1]; /* Add address of second element */ ar [1]. data = 99; /* Add data to second element */ 16 ar [1]. nextPtr = &ar [2]; /* Add address of third element */ ar [2]. data = -7; /* Add data to third element */ 18 ar [2]. nextPtr = 0; /* mark end of list */
  • 37. 436 File & Data Structure 20 /* follow pointers */ lp = ar; 22 while (lp) { printf("contents %dn", lp ->data ); 24 lp = lp ->nextPtr ; } 26 exit ( EXIT_SUCCESS ); } ✌ ✆ ✞ contents 5 contents 99 contents -7 ✌ ✆ Linked List (Pointer) A node in a list is memory location from where new data is stored. In C, a node is created like ✞ 1 struct myNode { int data ; 3 struct myNode *nextPtr ; }; ✌ ✆ Above structure has two elements, one for storing data and other for storing the address of next element. Hence, each structure of a linked list is group of two contents, ‘data’ and ‘address of next data location’. ✞ #include <stdio.h> 2 #include <stdlib.h> 4 struct myNode { int data ; 6 struct myNode *nextPtr ; }; 8 void Push (struct myNode ** myP , int value) { 10 struct myNode* cNode = (struct myNode*) 12 malloc(sizeof (struct myNode)); cNode ->data = value; 14 cNode ->nextPtr = (* myP); (* myP) = cNode; 16 printf("Value is %d at address %xn",cNode ->data , &cNode ->data ); printf("Address of next value %d is : %xn" ,(cNode ->data +1) , cNode ->nextPtr); 18 } 20 int main () {
  • 38. 3.3. DATA STRUCTURES 437 struct myNode* head = NULL ; 22 int i=5; while(i>0){ 24 Push (&head , i); i--; 26 } return 0; 28 } ✌ ✆ ✞ urrent value is 5 at address of 215b010 --<--+ Address of next value 6 is : 0 (end of list ) | Current value is 4 at address of 215c040 <-+ | Address of next value 5 is : 215b010 ->-->-|-+ Current value is 3 at address of 215c060 | Address of next value 4 is : 215c040 ->-->-+ Current value is 2 at address of 215c080 Address of next value 3 is : 215c060 Current value is 1 at address of 215c0a0 Address of next value 2 is : 215c080 ✌ ✆ Above output is analyse in pair of output line. First line givens the stored value and memory address where it is stored. Second line gives the address of previous linked element. We can add a node by pushing a value at the beginning of the linked list. For example, here we take a linked list like 4 0×042a 0×1225 7 0×1225 0×a22c 9 0×a22c 0×a2cc myP NULL and we want to add data 6 at the beginning of the linked list. Initially the memory address of ‘myP’ pointer is ‘0×042a’. A new linked block (‘myNode’) is created as shown below. Data (value 6) is pushed (at ‘0×d425’ say). The initial pointer address of ‘myP’ is linked to the ‘nextPtr’ of newly created block and ‘myP’ is assigned the address of this created block. I.e. now ‘myP’ is pointing to ‘0×042a’. 6 0×d425 0×042a 4 0×042a 0×1225 7 0×1225 0×a22c 9 0×a22c 0×a2cc myP NULL
  • 39. 438 File & Data Structure The C code for pushing data at the beginning of the linked list are given below: ✞ #include <stdio.h> 2 #include <stdlib.h> 4 struct myNode { int data ; 6 struct myNode *nextPtr ; }; 8 void Push (struct myNode ** myP , int value) { 10 struct myNode* childNode = (struct myNode*) 12 malloc(sizeof (struct myNode)); childNode ->data = value; 14 childNode ->nextPtr = (* myP); (* myP) = childNode ; 16 } 18 void printList (struct myNode *currentNodePtr ) { while (currentNodePtr != NULL ) { 20 printf(" %d ", currentNodePtr ->data ); currentNodePtr = currentNodePtr ->nextPtr; 22 } } 24 int main () { 26 struct myNode* head = NULL ; Push (& head , 9); 28 Push (& head , 7); Push (& head , 4); 30 Push (& head , 6); printf("Linked list is: "); 32 printList (head ); return 0; 34 } ✌ ✆ ✞ Linked list is: 6 4 7 9 ✌ ✆ We can insert a node by adding a value inbetween of the linked list. For example, here we take a linked list like 4 0×042a 0×1225 7 0×1225 0×a22c 9 0×a22c 0×a2cc myP NULL
  • 40. 3.3. DATA STRUCTURES 439 and we want to add data 6 inbetween of the linked list. A new linked block (‘myNode’) is created after the second list element as shown below. Data (value 6) is inserted (at ‘0×d425’ say). The ‘nextPtr’ of newly created block is assigned the address of data of 3rd element. Address of inserted data of the newly inserted block is assigned to the ‘nextPtr’ of 2nd element of the linked list. 4 0×042a 0×1225 7 0×1225 0×d425 6 0×d425 0×a22c 9 0×a22c 0×a2cc myP NULL The C code for pushing data at the beginning of the linked list are given below: ✞ 1 #include <stdio.h> #include <stdlib.h> 3 struct myNode { 5 int data ; struct myNode *nextPtr ; 7 }; 9 void Push (struct myNode ** myP , int value) { struct myNode* childNode = 11 (struct myNode*) malloc(sizeof (struct myNode)); 13 childNode ->data = value; childNode ->nextPtr = (* myP); 15 (* myP) = childNode ; } 17 void Insert(struct myNode* NodeIndex , int value) { 19 if (NodeIndex == NULL ) { printf("Node index cannot be NULL "); 21 return; } 23 struct myNode* childNode = (struct myNode*) 25 malloc(sizeof (struct myNode)); childNode ->data = value; 27 childNode ->nextPtr = NodeIndex -> nextPtr; NodeIndex ->nextPtr = childNode ; 29 } 31 void printList (struct myNode *currentNodePtr ) { while (currentNodePtr != NULL ) {
  • 41. 440 File & Data Structure 33 printf(" %d ", currentNodePtr ->data ); currentNodePtr = currentNodePtr ->nextPtr; 35 } } 37 int main () { 39 struct myNode* head = NULL ; Push (& head , 9); 41 Push (& head , 7); Insert(head ->nextPtr , 6); 43 Push (& head , 4); printf("Linked list is: "); 45 printList (head ); return 0; 47 } ✌ ✆ ✞ Linked list is: 4 6 7 9 ✌ ✆ Similarly, we can append elements in a linked list. The C code for appending elements in linked list are given below: ✞ 1 #include <stdio.h> #include <stdlib.h> 3 struct myNode { 5 int data ; struct myNode *nextPtr ; 7 }; 9 void Push (struct myNode ** myP , int value) { struct myNode* childNode = 11 (struct myNode*) malloc(sizeof (struct myNode)); 13 childNode ->data = value; childNode ->nextPtr = (* myP); 15 (* myP) = childNode ; } 17 void Append(struct myNode ** myP , int value) { 19 struct myNode* childNode = (struct myNode*) 21 malloc(sizeof (struct myNode)); struct myNode *last = *myP; 23 childNode ->data = value; childNode ->nextPtr = NULL ; 25 if (* myP == NULL ) { *myP = childNode ; 27 return; } 29 while (last ->nextPtr != NULL ) last = last ->nextPtr ;
  • 42. 3.3. DATA STRUCTURES 441 31 last -> nextPtr = childNode ; return; 33 } 35 void printList (struct myNode *currentNodePtr ) { while (currentNodePtr != NULL ) { 37 printf(" %d ", currentNodePtr ->data ); currentNodePtr = currentNodePtr ->nextPtr; 39 } } 41 int main () { 43 struct myNode* head = NULL ; Push (& head , 7); 45 Push (& head , 1); Append (&head , -15); 47 Push (& head , 10); Append (&head , -45); 49 Push (& head , 7); Push (& head , -5); 51 printf("Linked list is: "); printList (head ); 53 return 0; } ✌ ✆ ✞ Linked list is: -5 7 10 1 7 -15 -45 ✌ ✆ To delete an element from a linked list, we just bypass the elements being deleted as shown in the following figures. 4 0×042a 0×1225 7 0×1225 0×a22c 9 0×a22c 0×a2cc myP NULL We have a link list as shown above and we want to delete element having value 7. To do so, we just skip this element and linked first element with third element. as shown below: 4 0×042a 0×a22c 7 0×1225 0×a22c 9 0×a22c 0×a2cc myP NULL The C code for appending elements in linked list are given below:
  • 43. 442 File & Data Structure ✞ 1 #include <stdio.h> #include <stdlib.h> 3 struct myNode { 5 int data ; struct myNode *nextPtr ; 7 }; 9 void Push (struct myNode ** myP , int value) { struct myNode* childNode = 11 (struct myNode*) malloc(sizeof (struct myNode)); 13 childNode ->data = value; childNode ->nextPtr = (* myP); 15 (* myP) = childNode ; } 17 void deleteNode (struct myNode ** head_ref , int key) { 19 struct myNode* temp = *head_ref , *prev ; if (temp != NULL && temp ->data == key) { 21 * head_ref = temp ->nextPtr; free (temp ); 23 return; } 25 while (temp != NULL && temp ->data != key) { prev = temp ; 27 temp = temp ->nextPtr ; } 29 if (temp == NULL ) return; prev -> nextPtr = temp ->nextPtr; 31 free (temp ); } 33 void printList (struct myNode *currentNodePtr ) { 35 while (currentNodePtr != NULL ) { printf(" %d ", currentNodePtr ->data ); 37 currentNodePtr = currentNodePtr ->nextPtr; } 39 } 41 int main () { struct myNode* head = NULL ; 43 Push (& head , 9); Push (& head , 7); 45 Push (& head , 4); printf("Created Linked list is: "); 47 printList (head ); deleteNode (&head , 4); 49 printf("nCreated Linked list is: "); printList (head );
  • 44. 3.3. DATA STRUCTURES 443 51 return 0; } ✌ ✆ ✞ Created Linked list is: 4 7 9 Created Linked list is: 7 9 ✌ ✆ 3.3.7 Heap A heap is a specialized tree-based data structure that satisfies the heap property that if P is a parent node of C, then the key (the value) of P is either greater than or equal to (in a max heap) or less than or equal to (in a min heap) the key of C. The node at the “top” of the heap (with no parents) is called the root node. The heap is one maximally efficient implementation of an abstract data type called a priority queue, and in fact priority queues are often referred to as “heaps”, regardless of how they may be implemented. 100 193 36 17 2 25 1 2 7 Heaps are implemented in an array of either fixed size or of dynamic size. Each heap is required to perform internal operation during the insertion, deletion or appending of an element. The most common form of heap is binary heap. Binary heaps are represented by using an array only. 0 1 2 3 4 5 6 7 8 9 10 0 1 2 3 4 5 6 7 8 9 10 Figure 3.4: Zero-based Array. The first or last element of the array is root. The next two elements of the array contain its children. The next four contain the four children of the two child nodes, etc. Thus the children of the node at position n would be at positions 2n and 2n + 1 if index
  • 45. 444 File & Data Structure of the first element of an array is started with one, or 2n + 1 and 2n + 2 if index of the first element of an array is started with zero. 1 2 3 4 5 6 7 8 9 10 11 1 2 3 4 5 6 7 8 9 10 11 Figure 3.5: One-based Array. Construction One dimensional array based heap is constructed by creating an array of requisite size as shown below: ✞ int myHeap [20]; // heap of size of 20 elements ✌ ✆ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 index Each heap cell is of four bytes size and one-based indexed. We can add twenty elements in these cells. Add/Insert an Element Let an element is being added in the one-base array at the index of 2n. This element is compared with all previous corresponding child nodes at index locations given by n = n/2. If value at a child node is greater than the element being added/inserted, it is swapped mutually. This process undergo until the element is not become greater than the value at previous child node. Consider an one-based one dimensional array as shown below: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 index 2 4 6 9 3 Let current element 3 is being added at the index location 16. Now, 3 is compared with value at index location 16/2 = 8, i.e. with value 9. Here, 3 < 9, hence 9 is placed in the index location 16 and 3 is being try to put at index location 8 as shown below: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 index 2 4 6 9 3
  • 46. 3.3. DATA STRUCTURES 445 Now, 3 is being put at the index location 16/2 = 8, but before inserting it at this location, we again compare it with the value stored at index location 8/2 = 4. So, again 3 < 6, hence 6 is placed at the index location 8 as shown below: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 index 2 4 6 9 3 This process is iterated until 3 became larger than value at previous child node. Now, 3 is being put at the index location 8/2 = 4, but before inserting it at this location, we again compare it with the value stored at index location 4/2 = 2. So, again 3 < 4, hence 4 is placed at the index location 4 as shown below: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 index 2 4 6 9 3 Finally, 3 became larger than its previous corresponding child node where value 2 is stored. So, 3 is placed at index location 2 as shown below: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 index 2 3 4 6 9 The equivalent code example is given below: ✞ 1 void Insert(int v) { heapSize ++; 3 heap [ heapSize ] = v; int current_node = heapSize ; 5 while (heap [current_node / 2] > v) { heap [current_node ] = heap [current_node / 2]; 7 current_node /= 2; } 9 heap [ current_node ] = v; } ✌ ✆ Remove an Element In heap an element can be deleted, but after each removal of an element, the heap is reorganized. Consider a one-based one-dimensional heap array as shown below: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 index 2 3 4 6 9 Suppose we want to remove the element 4 at index location 4. To do this, we first remove it from the list as shown below:
  • 47. 446 File & Data Structure 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 index 2 3 6 9 Now, we should have rearrange all the elements right side to the element being re- moved, i.e. element at index location 8 shall be shifted to index location 4 and element at index location 16 shall be shifted to index location 8 and so on. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 index 2 3 6 9 Finally, the new heap list shall be looked like as given below: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 index 2 3 6 9 3.3.8 Tree Binary tree is the data structure to maintain data into memory of program. There exists many data structures but they are used as per their performance. In binary tree, each node can have two child nodes and each child node can itself be a small binary tree. 1 3 4 7 6 9 8 In this binary tree, we add a child node to a parent node. Child nodes have the reference to their parent node. By this way each child node is linked with its parent node & parent node is linked with its parent node and so on. Create Tree Structure Here, we have create a coordinate based tree nodes. A node contains the parent’s coor- dinate, current node coordinate and node value. The node structure is like (xold, yold, xnew, ynew, value). For it, a structure is created as shown below: ✞ struct TreeData { 2 int x_node; int y_node; 4 int x_child_node ; int y_child_node ;
  • 48. 3.3. DATA STRUCTURES 447 6 int val; }; 8 /* Current node coordinates .*/ 10 struct NewCoord { int x; 12 int y; } nc; ✌ ✆ Insert Tree Data First we get the new coordinate of current node, i.e. child node. The value is linked with parent node and saved in a data file. A node is in a sequential structure of xold, yold, xnew, ynew, value. ✞ 1 int insert(struct TreeData *td , FILE *fp , int x_node , int y_node , int val) { int xnew ; 3 int ynew ; xnew = nc.x + 1; 5 ynew = nc.y + 1; if (xnew < x_node || ynew < y_node) { 7 return 1; } 9 td ->x_node = x_node; td ->y_node = y_node; 11 td ->x_child_node = xnew ; td ->y_child_node = ynew ; 13 td ->val = val; fwrite(td , sizeof ( struct TreeData ), 1, fp); 15 nc.x = xnew ; nc.y = ynew ; 17 return 0; } ✌ ✆ Display Tree Data Here we search all the child nodes and values of the parent node (xold, yold). Scann the file and put the output in console when parent node is equal to the supplied parent node. ✞ int view ( struct TreeData *td , FILE *fp , int x_node , int y_node) { 2 printf("%10s%10s%10s%10s%10sn", "parent x", 4 "parent y", "child x", 6 "child y", "Value"); 8 printf("%50sn"," ------------------------------------------------"); int s;
  • 49. 448 File & Data Structure 10 s = fread(td , sizeof (struct TreeData ), 1, fp); while (s > 0) { 12 if (td ->x_node == x_node && td ->y_node == y_node) { printf("%10d%10d%10d%10d%10dn", 14 td ->x_node , td ->y_node , 16 td -> x_child_node , td -> y_child_node , 18 td ->val); } 20 s = fread(td , sizeof (struct TreeData ), 1, fp); } 22 return 0; } ✌ ✆ Delete Tree Data In this step, we search the required parent node whose child node values are to be emptied. First the data from data file is saved into temporary file with deleted values of all child nodes. Original file is deleted and temporary file is renamed to the data file. ✞ 1 int delete(struct TreeData *td , FILE *fp , int x_node , int y_node) { int s; 3 FILE *tmp; tmp = fopen("Tmp.txt", "wb"); 5 s = fread(td , sizeof (struct TreeData ), 1, fp); while (s > 0) { 7 if (td ->x_node == x_node && td ->y_node == y_node) { td ->val = 0; 9 fwrite(td , sizeof (struct TreeData ), 1, tmp); } else { 11 fwrite(td , sizeof (struct TreeData ), 1, tmp); } 13 s = fread(td , sizeof (struct TreeData ), 1, fp); } 15 fclose(tmp); remove(fp); 17 rename("Tmp.txt", " TreeNode .txt"); return 0; 19 } ✌ ✆ Here is complete code for data tree. ✞ 1 #include <stdio.h> 3 /* Three data structure . x_node & y_node * *represents to the parent node . While * 5 *x_child_node & y_child_node represents * *to the child node . val is data value at* 7 *child node . Parent node is link of the*
  • 50. 3.3. DATA STRUCTURES 449 *child node .*/ 9 struct TreeData { int x_node; 11 int y_node; int x_child_node ; 13 int y_child_node ; int val; 15 }; 17 /* Current node coordinates .*/ struct NewCoord { 19 int x; int y; 21 } nc; 23 /* Insert data at current child node ,* *linked with its parent node . */ 25 int insert(struct TreeData *td , FILE *fp , int x_node , int y_node , int val) { 27 int xnew ; int ynew ; 29 xnew = nc.x + 1; ynew = nc.y + 1; 31 if (xnew < x_node || ynew < y_node) { return 1; 33 } td ->x_node = x_node; 35 td ->y_node = y_node; td ->x_child_node = xnew ; 37 td ->y_child_node = ynew ; td ->val = val; 39 fwrite(td , sizeof ( struct TreeData ), 1, fp); nc.x = xnew ; 41 nc.y = ynew ; return 0; 43 } 45 /* View all the child nodes of the parent node .*/ int view ( struct TreeData *td , FILE *fp , int x_node , int y_node) { 47 printf("%10s%10s%10s%10s%10sn", "parent x", 49 "parent y", "child x", 51 "child y", "Value"); 53 printf("%50sn"," ------------------------------------------------"); int s; 55 s = fread(td , sizeof (struct TreeData ), 1, fp); while (s > 0) { 57 if (td ->x_node == x_node && td ->y_node == y_node) { printf("%10d%10d%10d%10d%10dn",
  • 51. 450 File & Data Structure 59 td ->x_node , td ->y_node , 61 td -> x_child_node , td -> y_child_node , 63 td ->val); } 65 s = fread(td , sizeof (struct TreeData ), 1, fp); } 67 return 0; } 69 /* Delete all values at parent node .*/ 71 int delete(struct TreeData *td , FILE *fp , int x_node , int y_node) { 73 int s; FILE *tmp; 75 tmp = fopen("Tmp.txt", "wb"); s = fread(td , sizeof (struct TreeData ), 1, fp); 77 while (s > 0) { if (td ->x_node == x_node && td ->y_node == y_node) { 79 td ->val = 0; fwrite(td , sizeof (struct TreeData ), 1, tmp); 81 } else { fwrite(td , sizeof (struct TreeData ), 1, tmp); 83 } s = fread(td , sizeof (struct TreeData ), 1, fp); 85 } fclose(tmp); 87 remove(fp); rename("Tmp.txt", " TreeNode .txt"); 89 return 0; } 91 /* Main function part .*/ 93 int main () { FILE *fp; 95 struct TreeData td; /* Open file and write tree data .*/ 97 fp = fopen("TreeNode .txt", "wb+"); int i = 0; 99 while (i < 100) { insert (&td , fp , i % 5, i % 6, i); 101 i++; } 103 fclose(fp); /* Open file and Delete specific tree node data .*/ 105 fp = fopen("TreeNode .txt", "rb"); delete (&td , fp , 1, 1); 107 fclose(fp); /* Open file and view tree node data .*/ 109 fp = fopen("TreeNode .txt", "rb");
  • 52. 3.3. DATA STRUCTURES 451 view (&td , fp , 1, 1); 111 fclose(fp); return 0; 113 } ✌ ✆ 3.3.9 Binary Tree
  • 54. 4.1. ERROR HANDLING FUNCTIONS 453 4Miscellaneous 4.1 Error Handling Functions Following functions are used for handling of errors arises when a program is compiled or executed. Some of the errors are thrown by compiler when a program is compiles. These errors arise if we try to use undefined functions, misprints or using wrong procedures. Run time errors arise when we try to access restricted or denied memory locations, try to create a wrong file structure or wrote a program which is not compatible to hardware/software. 4.1.1 clearerr function The synopsis of the function is ✞ 1 #include <stdio.h> void clearerr (FILE *stream); ✌ ✆ The clearerr function clears the end-of-file and error indicators for the stream pointed-by ‘stream’. A simple example is ✞ #include <stdio.h> 2 int main () { 4 FILE * fName; fName = fopen("F.txt", "r"); 6 if (fName == NULL ) perror("Can not open the file "); 8 else { fputc(’x’, fName); 10 if (ferror(fName)) { printf("Can not write in file .n"); 12 clearerr (fName); } 14 fgetc(fName); if (! ferror(fName)) 16 printf("Reading from file .n"); fclose(fName); 18 } return 0; 20 } ✌ ✆ ✞ Can not write in file . Reading from file . ✌ ✆
  • 55. 454 Miscellaneous 4.1.2 ferror function The synopsis of the function is ✞ #include <stdio.h> 2 int ferror(FILE *stream); ✌ ✆ The ferror function tests the error indicator for the stream pointed-by ‘stream’ and returns nonzero if and only if the error indicator is set for stream, otherwise it returns zero. A simple example is ✞ #include <stdio.h> 2 int main (void ) { 4 int a; FILE *fp; 6 /* file .txt must be in executable ’s dir*/ fp = fopen("file .txt", "rb"); 8 /* Read single ints at a time , stopping on EOF or error:*/ while (fread(&a, sizeof (int), 1, fp), !feof (fp) && !ferror(fp)){ 10 printf("I read %dn", a); } 12 if (feof (fp)) printf("End of file was reached .n"); 14 if (ferror(fp)) printf("An error occurred .n"); 16 fclose(fp); return 0; 18 } ✌ ✆ ✞ I read 1735287116 I read 1701279073 End of file was reached . ✌ ✆ 4.1.3 perror function The synopsis of the function is ✞ 1 #include <stdio.h> void perror(const char *s); ✌ ✆ The perror function maps the error number in the integer expression errno to an error message. It writes a sequence of characters to the standard error stream thus: first, if ‘s’ is not a null pointer and the character pointed-by ‘s’ is not the null character, the string pointed-by ‘s’ followed by a colon (:) and a space; then an appropriate error message string followed by a new-line character. The contents of the error message are the same as those returned by the strerror function with the argument errno, which are implementation-defined. A simple example is
  • 56. 4.1. ERROR HANDLING FUNCTIONS 455 ✞ #include <stdio.h> 2 /* Must include to see " errno"*/ #include <errno.h> 4 int main (void ) { 6 if (fseek(stdin , 10L, SEEK_SET ) < 0) perror("fseek"); 8 /* Stop using this stream */ fclose(stdin); 10 if (fseek(stdin , 20L, SEEK_CUR ) < 0) { if (errno == EBADF) { 12 perror("fseek again , EBADF"); } else { 14 perror("fseek again"); } 16 } return 0; 18 } ✌ ✆ ✞ fseek: Illegal seek fseek again , EBADF: Bad file descriptor ✌ ✆ 4.1.4 Segmentation Fault Segmentation fault is shown by different hardware and operating system with different ways. Some prominent reason of segmentation fault are 1. Dereferencing null pointers. 2. Accessing non existent pointer. 3. Attempting to access a nonexistent memory address. 4. Attempting to access memory the program does not have rights to. 5. Attempting to write read-only memory. 6. Dereferencing or assigning to an uninitialized pointer. 7. Dereferencing or assigning to a freed pointer. 8. A buffer overflow. 9. A stack overflow. 10. Attempting to execute a program that does not compile correctly.
  • 57. 456 Miscellaneous ✞ #include <stdio.h> 2 int main () { 4 FILE *fl; /* File pointer */ fclose (fl);/* Trying to close file pointer * 6 * that was never opened before. * * Cause for segmentation fault. */ 8 return 0; /* Return sucess. */ } ✌ ✆ 4.2 Reserved Keyword There are 32 keywords in C89 while 37 reserve keywords in C99 and 44 reserve keywords in C11. These keywords are solely reserved for internal use by C compilers. They can not be redefined by programmer or can not be used as literals. The list of reserved keywords is given below. auto double int static break else long struct case enum register switch char extern restrict union const float return unsigned continue for short void default goto signed volatile do if sizeof while Bool Complex Imaginary inline restrict Alignas Alignof Atomic Generic Noreturn Static assert Thread local 4.3 Case Sensitivity C identifiers are case sensitive i.e. myname, MYNAME, and MyName are the names of three different objects. Some linker may map external identifiers to a single case, although this is uncommon in most modern linker. See the following example, in which two variables ‘y’ and ‘Y’ are declared and initialized. They are treated as two different variables and can be accessed differently. ✞ 1 #include <stdio.h> 3 int main () { // Declare a variable y 5 int y = 1; // Declare a variable Y 7 int Y = 2; printf("y is %d and Y is %dn", y, Y);
  • 58. 4.4. COMMENTING 457 9 return 0; } ✌ ✆ ✞ y is 1 and Y is 2 ✌ ✆ 4.4 Commenting Commenting inside the C code is a beautiful feature of C language. It provides the utility for writing managed codes. Commenting occurs within the C codes. It may be of a single line or can span in multiple lines. There are two way of commenting. First is single line commenting which started with ‘//’. Anything written in the line started with ‘//’ are skipped by the C compilers. Presence of another ‘//’ in the same line does not end the single line comment. Second method is multi-line commenting. Text starting with the token ‘/*’ are treated as a comments and ignored. The multi-line comments are ended at next token ‘*/’. ✞ 1 #include <stdio.h> 3 int main () { // Declare a variable // as y 5 int y; /* <-- given expression * 7 *y = (5 + 3 - 4) % 2 * *is computed in steps* 9 *y = (8 - 4) % 2 * *y = 4 % 2 = 0 -->*/ 11 y = (5 + 3 - 4) % 2; printf("Result is : %dn", y); 13 return 0; } ✌ ✆ ✞ Result is : 0 ✌ ✆
  • 60. 5.1. THROUGH NETBEAN 459 5Library In computer science, there are two types libraries. (i) A static library is a collection of object files which contain library routines and data. It is built in such a way that the link editor will incorporate a copy of only those object files that hold the functions and data referenced in the program into the executable at link time. (ii) A shared library is a shared object file that contains functions and data. It is built in such a way that the link editor will only store in the executable the name of the shared library and information about the symbols referenced by the executable. At run time the dynamic linker, a.k.a. the program interpreter in ELF, will map the shared library into the virtual address space of the process image of the executable and resolve by name the symbols in the shared library used by the executable. That is process is also called dynamic linking. Here, we will write example code for linking static libraries in C. There are three steps of static library use. First is generation of library, second is linking of library and third is its application. 5.1 Through NetBean 5.1.1 Create Library To create a library first create a C static or dynamic library project “myLib” in Netbean with cygwin gcc compiler. Create two files, myFunc.c and myFunc.h within the “myLib” project. The codes of these two files are respectively ✞ 1 #include <stdio.h> 3 void myFunc(void ){ puts ("Hello , I’m a shared library "); 5 } ✌ ✆ ✞ 1 #ifndef MYFUNC_H #define MYFUNC_H 3 #ifdef __cplusplus 5 extern "C" { #endif 7 // static library function 9 extern void myFunc(void ); 11 #ifdef __cplusplus } 13 #endif
  • 61. 460 Library 15 #endif /* MYFUNC_H */ ✌ ✆ Open project properties and click on C-Compiler or Linker option. Set tool to “gcc - shared”. Here, keyword “-shared” makes a library shareble. Compile this library and you will get a library for use with other program. 5.1.2 Link Library Now create second project in Netbean with MinGW, say ‘myProg’. Copy your generated library in this new project (say ‘myProg’) from where you can use it. Open the project property and go to the linker and add following to linker: ✞ 1 gcc -L"<path to library >" -l<static/ dynamic lib name > ✌ ✆ Here, ‘path to library’ is absolute path of your generated library that is put within your ‘myProg’ project or else where. Copy ‘myFunc.h’ into source directory of this new project and create new “main.c” file. The code of main file are ✞ 1 #include <stdio.h> #include "myFunc.h" 3 int main (void ) { 5 puts ("This is a shared library test ..."); myFunc (); 7 return 0; } ✌ ✆ Compile and build this program with MinGW gcc compiler and run this program. You will get the desire output. ✞ This is a shared library test ... Hello , I’m a shared library ✌ ✆ 5.2 From Command Line 5.2.1 Create Library Create two files, myFunc.c and myFunc.h with following codes and put them under a directory (say “C: myLib”) that is accessible to you. ✞ #include <stdio.h> 2 void myFunc(void ){ 4 puts ("Hello , I’m a shared library "); } ✌ ✆
  • 62. 5.2. FROM COMMAND LINE 461 ✞ 1 #ifndef MYFUNC_H #define MYFUNC_H 3 #ifdef __cplusplus 5 extern "C" { #endif 7 // static library function 9 extern void myFunc(void ); 11 #ifdef __cplusplus 13 } #endif 15 #endif /* MYFUNC_H */ ✌ ✆ From the command prompt, we can create static and dynamic libraries by using following commands with cygwin gcc. ✞ gcc -fPIC -c -o myFunc.o myFunc.c -I"C: myLib" 2 gcc -shared -o libmyFunc .dll myFunc.o ✌ ✆ Here, ‘-fPIC’ tells GCC that to create Position Independent Code using relative addresses rather than absolute addresses because these libraries can be loaded multiple times. Here, this flag may be omitted. If environment for ‘gcc’ compiler is not registered then use absolute path of the gcc executable like “C: MinGW bin gcc.exe”. ‘-I’ flag is used to add the directory where relevant header files are placed. Here, the prefix “lib” to ‘myFunc.dll’ required when we link this library to a program during program’s compilation with ‘-l’ flag identifier. Now out library is ready to be used. 5.2.2 Link Library Write a new program file “main.c”. The code of main file are ✞ #include <stdio.h> 2 #include "myFunc.h" 4 int main (void ) { puts ("This is a shared library test ..."); 6 myFunc (); return 0; 8 } ✌ ✆ Copy ‘myFunc.h’ into the same directory (say “C: myLib”) where this code file is placed. Now, compile this program file with MinGW gcc compiler as command given below:
  • 63. 462 Library ✞ gcc -c -o main .o main .c -I"C: myLib" 2 gcc -o main .exe main .o -L"C: myLib" -lmyFunc ✌ ✆ Here, “-L” flag represents to library path where user’s library is placed. “-l” represents to linked library name with the user’s program. “-I” represents to include path of header files. Name of static or dynamic library is supplied without prefix “lib” and extension name “.dll”. The flag ‘-l’ searches for the named library by pre-pending ‘lib’ automatically. If libraries are placed in the same directory (say “C: myLib”) where program file is then use following modified command: ✞ gcc -o main .exe main .o ./ -lmyFunc ✌ ✆ The output of above program is ✞ This is a shared library test ... Hello , I’m a shared library ✌ ✆ Here, both static and dynamic libraries can be used with C program. But dynamic libraries are preferred over the static libraries as and when dynamic libraries are upgraded, program does not need recompilation with upgraded dynamic libraries. 5.3 Load Library Dynamically In C programming, with POSIX system, we can load a library dynamically by using functions dlopen(), dlsym() and dlclose(). These functions are found in ‘dlfcn.h’. Note that this library only loaded library function for its calling. It does not check input and output parameters. Parameters are checked by function itself when it is called. dlopen This function is used to open a static or dynamic library from user’s directory and reading of its export table that contains the function names of the library. It accepts two arguments. First is library name with absolute/relative path and second is mode of opening of the library. It returns a ‘handle’ pointing to the library. If it is unable to locate/open a file, it returns NULL or an error value. If NULL is used as file name argument to this function, then it will export symbols in the executable for currently loaded shared libraries via dlsym function. ✞ void *myLib = dlopen(<name >, <mode >) ✌ ✆ Here name of library is constant character type and mode of opening of library is either of the ‘RTLD NOW’ (for immediate function binding), ‘RTLD LAZY’ (for lazy function binding), ‘RTLD GLOBAL’ or ‘RTLD LOCAL’. See the example below: ✞ 1 #include <stdio.h> #include <stdlib.h> 3 #include <dlfcn.h> 5 int main () { void * myLib;
  • 64. 5.3. LOAD LIBRARY DYNAMICALLY 463 7 myLib = dlopen("libcdy.dll", RTLD_LAZY ); if (myLib == NULL ) { 9 printf("Can not locate library %sn", "libcdy.dll"); } 11 return EXIT_SUCCESS ; } ✌ ✆ dlsym After a shared library is loaded into the address space of the running process, this function is used to obtain the address of an exported symbol in that shared library. We can now access the function or data through the address returned from dlsym function. This function searches for the function supplied it to as its second argument and returns its address. If the function could not be found, it returns NULL. The return value must be casted to a proper function pointer before it can be used. Its syntax is looked like as ✞ void (* fptr )(); 2 fptr = dlsym(<handle >, <function name >); ✌ ✆ See the example below: ✞ #include <stdio.h> 2 #include <stdlib.h> #include <dlfcn.h> 4 int main () { 6 void * myLib; void (* fptr )(); 8 myLib = dlopen("libcdy.dll", RTLD_LAZY ); if (myLib != NULL ) { 10 fptr = dlsym(myLib , "myFunc"); if (! fptr ) { 12 printf("Can not locate function %sn", "myFunc"); } 14 /* Call the function through its pointer */ fptr (); 16 } else { printf("Error in opening %s library !!", "libcdy.dll"); 18 } if (myLib != NULL ) 20 dlclose (myLib); return EXIT_SUCCESS ; 22 } ✌ ✆ dlclose Each handle opened with dlopen() function must be closed by using dlclose() function. This function returns ‘-1’ if it failed to close a handle refering to the opened library. ✞ int v= dlclose (<handle >); ✌ ✆
  • 65. 464 Library dlerror This function is used to retrieve a text message that is describing to the most recent error occurred during the process of either of the functions dlopen(), dlsym() and dlclose(). ✞ 1 char *v= dlerror(void ); ✌ ✆