A Structure is a user defined data type. It is called a conglomerate i.e. mixed data type. A structure can hold any number of any data types under one name. Keyword struct is used to define such a data type .
Defining a structure :-
struct Datatypename
{
datatype membername ;
datatype membername ;
……
};
For e.g :
A point in space is associated with two dimensions x , y. We may represent a point as a data structure as follows
struct point /* point is a data type */
{
int x ;
int y ;
};
struct point P ; /* P is a variable of data type point
P.x = 90 ;
P.y = 10 ;
-----
and so on
Suppose we wish to store data about products , we may want a single data type that can store
a product code that may be an integer ,
a product name that may be a char array ,
rate that may be a float ,
quantity that may be an int ... etc .
It makes sense to define a single data type that can store all these types of data under one name . This data structure can then be manipulated meaningfully . We can create variables of this type which we have defined to suit our needs .
Members of the structure and the member operator :-
The different data within a structure are called as members . A dot operator called member operator is used to access each member of a structure. It is a binary operator , associates Left -> Right .
StructureVariablename . membervariablename
Difference between data type and variable :-
Here one must be clear that defining a structure is creation of a data type . It is merely informing the system that you want a bundle of such and such datatypes, so much of memory for a particular new data type You need to create variables of this type. Then only memory is allocated for that variable. The memory allocated is the total of all the memory requirements of all the members of that structure.
Program:
struct student /* student is a data type */
{
int rollno;
char name [ 10 ];
} ;
main ()
{
struct student stu = { 10, “sheetal“ } ;
/*
stu is a variable of type student .
Memory allocated = 10 + 2 bytes
*/
printf(“ Name = %s Roll no. = %d “ , s.name, s.rollno);
}
Memory Mapping:
Allocation: 2 Bytes 10 Bytes
Values 10 “SHEETAL”
Members s.rollno s.name
Structure tag: -
Name of a structure data type like point above is called as tag .A tag helps us to declare the structure variables, pass it to a function and so on. An anonymous structure like
struct {
int x , y ;
} v1 ;
declares a variable v1 with 2 members v1.x , v1.y . But the tag is missing here which means there is no way to refer to this structure definition in further coding.
Using typedef in a structure definition :-
typedef struct
{
char title[10];
char author[10];
int pages ;
} book ;
The above definition creates a datatype book which can be used without using the keyword struct in variable declaration as follows
book b1 , b2 , b3 ;
Array of structures :-
You create an array of structures the same way as you create any other array and manipulate each array element with index.
struct product
{
int code;
char description [10];
float rate;
int qty;
float amt; /* might create linker error */
/* Read footnote ** below */
} ;
main( )
{
int j;
float total = 0;
struct product p [ 3 ] ; /* p[3] is an array of products */
for( j = 0 ; j <3; j++ )
{
printf(“ Enter code : “);
scanf(“%d”, &p[j] . code);
printf(“ Enter Description : “);
scanf(“%s”, p[j] . description) ;
/* No Address Operator used above since an array name is an address */
printf(“ Enter Rate : “);
scanf(“%f”, &p[j] . rate);
printf(“ Enter Quantity : “);
scanf(“%d”, &p[j] . qty);
p[j].amt = p[j].rate * p[j].qty;
total += p[j].amt;
}
/* Now print the data in a tabular form */
gotoxy(1,23);
printf(“\nPress any key to see the product report…….”);
getch( ) ; clrscr( ) ;
printf(“%10s%15s% %10s%10s%10s\n\n”, “Code” , “Product” , “Rate” , “Quantity” , “Amount”);
for( j = 0 ; j < 3 ; j++ )
printf(“%10d%15s%10.2f%10d%10.2f\n\n”, p[j].code, p[j].description, p[j].rate , p[j].qty, p[j].amt );
printf(“\n\n\nTotal Bill Amount Rs. %.2f” , total );
getch();
return 0 ;
}
A pointer can be used to access and manipulate members of a structure , pass to a function as a reference etc.An arrow operator -> is used to access members of a structure with a structure pointer .
Program:
void main()
{
struct point P = { 100 , 200 }; /* struct point defined above */
struct point *ptr ;
ptr = &p ; /* ptr now points to p */
clrscr( ) ;
printf(“P.x = %d P.y = %d\n” , P.x , P.y );
printf(“ptr->x = %d ptr -> y = %d” , ptr -> x , ptr -> y );
getch( ) ;
}
Dynamic memory allocation with pointers:-
When we use structure pointers in a program, if we wish to accept and store data then first we must allocate sufficient memory using malloc( )
For e.g
void main( )
{
struct product *p ;
/* struct product defined above , p is a pointer */
clrscr( ) ;
/* request enough memory to store one product data */
p = (struct product *) malloc ( sizeof(struct product) ) ;
/*
remember malloc( ) returns a void * . So you need to type
cast the return pointer to a struct student *
*/
if (p == NULL ) /* Did we succeed in allocation ?? */
{
printf(“Allocation failure”);
exit(1) ;
}
printf(“Enter Product Description , Code , Rate , Quantity :- “);
scanf ( “%s%d%f%d” , p->description , &p -> code , &p -> rate , &p -> qty );
p -> amt = p -> rate * p -> qty ;
printf(“Product Code : %d\nDescription : %s\n Rate Rs.%.2f \nQuantity : %d \n Please Pay Rs. %.2f “ ,
p -> code , p -> description , p -> rate , p-> qty , p -> amt );
getch( ) ;
}
Passing structures to functions :- Structures can be passed in and out of functions like any normal data
void Show(struct product p ) {…….}
Function Show( ) takes a structure variable as an argument . Values are passed to the function
struct product Create(struct product p ) {…….}
Function Create( ) takes a structure and returns a structure of type product. Only values are passed. Original data is intact.
void ChangeProduct(struct product *) { …….. }
as its argument. This is a pass by reference . Any change made to the data is reflected to the calling function.
struct product * FuncA(struct product *p ) {…….}
Function FuncA( ) takes a pointer to a structure variable and returns a pointer to structure variable of type product.
Self referential structures
The one restriction on structure nesting is that a structure cannot contain an image of itself. That is, a structure cannot contain a member defined with the same tag as the outside structure. Such a construct would be an infinite recursion. It is legal, however, to have a structure contain a pointer to structure of the same type,. This is called as a self referential structure. This is a useful data structure in managing data as a linked list, tree etc..
Linked Lists and self referential structures
Suppose we have no idea how much of data we are going to load into memory ?? Then an array is not useful as here we are limited by allocation which is fixed. Even an array of pointers would fail as we have to limit ourselves to some specific number of pointers A linked list is a useful data structure for such a purpose. A linked list allows virtually to load any amount of data in memory. A link list uses self referential pointers to pick up the location of the next data.
struct student
{
char name[10];
int age;
struct student *ptr ;
/* ptr is a pointer to a structure of type student
} ;
The above data structure is used to create, store and manipulate a linked list.
· A linked list is a collection of items (also called as nodes)
· Every node in the list contains some data and an address (pointer)
· This pointer points to the next data .
· The list ends when this pointer field is NULL .
· Every time we want to add some data we create a new node. Such a list is called a singly linked list
· If a node has two pointers - a pointer to the previous node and a pointer to the next node , then such a data structure is called as a doubly linked list.
Operations on a linked list :-
A list may be created, traversed (visit each and every node and pick up data from there), data can be inserted , sorted , data can be deleted. Deletion and sorting involve movement (swapping) of pointers and not of actual data.
Head and tail of a list :-
The first node is the head and the last node is the tail. You need to hold these addresses so that the list can be traversed . A singly linked list can only be traversed in one direction (head to tail) while a doubly linked list can be traversed in both the directions
Creating a link list : -
struct node
{
char name[10] ;
struct node *next ;
};
struct node *head , *ptr , *previous ;
struct node * createNode ( ) ;
struct node * createNode ( )
{
struct node *t ;
t = (struct node *) malloc ( sizeof(struct node );
return t ;
}
main()
{
struct student *head , *ptr , *previous ;
int j = 1 ;
char ans = ‘Y’ ;
clrscr();
while(ans == ‘y’ || ans == ‘Y’ )
{
previous = ptr ;
ptr = createNode ( ) ;
if ( j++ == 1 )
head = ptr ; // Hold the address of the first node
printf(“ Enter Name : “ );
gets(ptr à name) ;
ptr -> next = NULL ;
previous -> next = ptr ;
printf(“One more name ? “);
fflush(stdin);
ans = getchar();
}
printf(“\nList created \nTraversing the list………\n”);
ptr = head ;
while(ptr != NULL )
{
printf(“Name : %s\n” , ptr -> name );
ptr = ptr -> next ; /* Move to the next node */
}
getch();
return 0 ;
}
** Linker Error : Floating points not linked
Using a float data type in a structure sometimes gives such an error
To overcome this problem add the following lines of code above main( )
void linkfloat(void)
{ float a = 0 , *b = &a ;
a = *b ;
}
No comments:
Post a Comment