• Tidak ada hasil yang ditemukan

STRUCTURES AND UNIONS

UNIT – IV

10.1 INTRODUCTION

• Arrays can be used to represent a group of data items that are belongs to the same type.

• Arrays are used to store large set of data and manipulate them.

• disadvantage of arrays is that all the elements stored in an array are to be of the same data type.

• If we need to use a collection of different data type items it is not possible using an array.

• When we require using a collection of different data items of different data types we can use a structure.

Structure is a method of packing data of different types.

• A structure is a convenient method of handling a group of related data items of different data types.

47

10.2 Array vs structures

1. An array is a collection of related data elements of same type. Structure can have elements of different types.

2. An array is derived data type whereas Structure is user- defined one.

3. Any array behaves like a built-in data type. All we have to do is to declare an array variable and use it. But in the case of a Structure, first, we have to design and declare a data structure before the variables of that type are declared and used.

48

10.3 DEFINING A STRUCTURE

Syntax

struct tag_name {

data type member1;

data type member2;

};

Note

1. The template is terminated with a semicolon.

2. While the entire definition is considered as a statement, each member is declared independently for its name and type in a separate statement inside the template.

3. The tag name can be used to declare structure variables of its type, later in the program.

struct book_bank {

char title[20];

char author[15];

int pages;

float price;

};

Create a structure Book_bank to store book details.

The keyword struct declares a structure to holds the details of four fields namely title, author, pages and price.

These are members or elements of the structures.

Each member may belong to different or same data type.

The tag name can be used to define objects that have the tag names structure.

The structure we just declared is not a variable by itself but a template for the structure.

49

10.4 DECLARING STRUCTURE VARIABLE

To access structure item, we require to create

structure variable (object).

• A structure variable declaration is similar to the declaration of variables of any other data types.

It includes the following elements:

1. The keyword struct.

2. The structure tag name.

3. List of variable names separated by names.

4. A terminating semicolon.

Syntax

struct structure_name variable_name;

We can declare structure variables using the tag name any where in the

program.

Example

struct lib_books book1,book2,book3;

• Declares book1,book2,book3 as variables of type struct lib_books each declaration has four elements of the structure lib_books.

• Structures do not occupy any memory until it is associated with the structure variable such as book1.

50

We can also combine both template declaration and variables declaration in one statement.

Example

struct lib_books {

char title[20];

char author[15];

int pages;

float price;

} book1,book2,book3;

The use of tag name is optional.

Example struct {

} book1, book2, book3 ;

• Declares book1, book2, book3 as structure variables representing 3 books but does not include a tag name for use in the declaration.

• This approach is not recommended for the two reasons.

1. Without tag name, we cannot use it for future declarations.

2. Normally, structure definitions appear at the beginning of the program file, before any variables or functions are defined. They may also appear before the main, along with macro definitions, such as #define. In such cases, the definition is global and can be used by other functions as well.

10.5 Type-Defined Structures

Syntax

typedef struct {

---

type member1;

type member2;

---

}type name;

• The type-name represents structure definition associated with it and therefore, can be used to declare structure variables as

type-name variable1,variable2,……….;

Note

1. The name type-name is the type definition name ,not a variable.

2. We cannot define a variable with typedef declaration.

52

10.6 ACCESSING STRUCTURE MEMBERS

• The link between a member and a variable is established using the member selection operator ‘.’ which is known as dot operator or period operator.

Example book1.price

• is the variable representing the price of book1 and can be treated like any other ordinary variable.

• we can assign variables to the members of book1

strcpy(book1.title,”basic”);

strcpy(book1.author,”Balagurusamy”); book1.pages=250;

book1.price=285.0;

Or We can use scanf statement to assign values like

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

scanf(“%d”,&book1.pages);

53

Example program

#include<stdio.h>

#include<conio.h>

struct student {

char name[20];

int num;

int mark;

};

void main() {

struct student s1,s2;

clrscr();

printf("Enter the name of student1:");

scanf("%s",s1.name);

printf("Enter the roll number of student1:");

scanf("%d",&s1.num);

printf("Enter the marks of student1:");

scanf(“%d",&s1.mark);

printf("Enter the name of student2:");

scanf("%s",s2.name);

printf("Enter the roll number of student2:");

scanf("%d",&s2.num);

printf("Enter the marks of student2:");

scanf(“%d",&s2.mark);

printf(“Students Details\n");

printf(“Student 1 details\n”);

printf("%s\n",s1.name);

printf("%d\n",s1.num);

printf(“%d\n",s1.mark);

printf(“Student 2 details\n”);

printf("%s\n",s2.name);

printf("%d\n",s2.num);

printf(“%d",s2.mark);

getch();

}

54

10.7 STRUCTURE INITIALIZATION

• A structure variable can be initialized at compile time.

Example 1 main() {

struct {

int weight;

float height;

} student={50,170.26};

……………………

} • This assigns 50 to student.weight and 170.26 to student.height.

• There is one-to-one correspondence between the members and their initializing values.

Example2 main() {

struct st_record {

int weight;

float height;

};

struct st_record student1={50,170.26};

struct st_record student2={60,180.75};

……………………

}

55

Example 3

struct st_record {

int weight;

float height;

}student1={50,170.26};

main() {

struct st_record student2={60,180.75};

……………………

} • The c language does not permit the initialization of individual structure members within the templates.

• The initialization must done only in the declaration of the actual variables.

• The compile-time initialization of a structure variable must have the following elements.

1. The keyword struct

2. The structure tag_name.

1. The name of the variable to be declared.

2. The assignment operator =.

3. A set of values for the members of the structure variable, separated by commas and enclosed in braces.

4. A terminating semicolon.

Rules for initializing structures

1. We cannot initialize the individual members inside the structure

template.

2. The order of values enclosed in braces must match the order of

members in the structure definition.

3. It is permitted to have a partial

initialization. We can initialize only the first few members and leave the remaining blank. The uninitialized members should be only at the end of the list.

4. The uninitialized members will be assigned default values. 56

10.8 COPYING & COMPARING STRUCTURE VARIABLES

copy

Two variables of the same structure type can be copied .

Example

If student1 and student2 belong to the same structure then

student1=student2;

student2= student1;

Comparision

The following statements are not permitted in c.

student1 == student2 student1 != student2

C does not permitted any logical operators on structure variables.

We can compare members individually.

structure class {

int no;

char name[20];

int marks;

};

void main() {

int x;

struct class stud1={101, “anu”,89};

struct class stud2={102, “banu”,80};

struct class stud3;

stud3=stud2;

x= ((stud3.no==stud2.no) && (stud3.marks ==

stud2.marks))?1:0;

if (x=1) {

printf(“\n student2 and student3 same\n”);

printf(“%d%s%d”,stud3.no,stud3.name,stud3.marks)

; } else {

printf(“student2 and student3 are different”);

} }

57

10.9 ARRAYS OF STRUCTURES

Declaring an array of structure is same as declaring an array of fundamental types.

An array is a collection of elements of the same type.

In an array of structures, each element of an array is of the structure type.

An array of structure is stored inside the memory in the same way as a multi- dimensional array.

Syntax

struct tag_name {

data type member1;

data type member2;

};

struct tag-name struct_array[size];

Example struct student {

char name[20];

int num;

int mark;

};

struct student stud[10];

58

EXAMPLE

#include<stdio.h>

#include<conio.h>

struct student {

char name[20];

int num;

int mark;

};

struct student stud[10];

void main() {

int i,n;

clrscr();

printf(“\n Enter the no. of students in a class:”);

scanf(“%d”, &n);

printf(“Enter the students detials one by one\n”);

for (i=0;i<n;i++) {

printf(“Enter the reg.no of the student %d :”, i+1) scanf(“%d”, &stud[i].num);

printf(“Enter the name of the student %d :”, i+1) scanf(“%s”, stud[i].name);

printf(“Enter the marks of the student %d :”, i+1) scanf(“%d”, &stud[i].mark);

}

for (i=0;i<n;i++) {

printf(“Reg.no of the student %d : %d”, i+1,stud[i].num);

printf(“Name of the student %d : %s”, i+1,stud[i].name);

printf(“Marks of the student %d : %d”, i+1,stud[i].mark);

}

getch();

}

59

10.10 ARRAYS WITHIN STRUCTURES

C permits the use of arrays as structure members.

Example

#include<stdio.h>

#include<conio.h>

struct student {

char name[20];

int num;

int mark[3];

int total;

};

struct student stud[10];

void main() {

int i,n,j;

clrscr();

printf(“\n Enter the no. of students in a class:”);

scanf(“%d”, &n);

printf(“Enter the students detials one by one\n”);

for (i=0;i<n;i++) {

printf(“Enter the reg.no of the student %d :”, i+1) scanf(“%d”, &stud[i].num);

printf(“Enter the name of the student %d :”, i+1) scanf(“%s”, stud[i].name);

printf(“Enter the marks of the student %d :”, i+1) stud[i].total=0;

for (j=0;j<3;j++) {

scanf(“%d”, &stud[i].mark[j]);

stud[i].total= stud[i].total+stud[i].mark[j];

} }

for (i=0;i<n;i++) {

printf(“\nReg.no of the student %d : %d”, i+1,stud[i].num);

printf(“\nName of the student %d : %s\n”, i+1,stud[i].name);

for (j=0;j<3;j++)

printf(“Marks of the student %d \t: %d”, i+1,stud[i].mark[j]);

printf(“\nTotal marks of the student %d : %d”, i+1,stud[i].total);

}

getch();

}

60

10.11 STRUCTURES WITHIN STRUCTURES

• Structure within a structure is called nested structure.

Example struct salary {

char name[20];

char dept[30];

struct {

int da;

int hra;

int cca;

}allowance;

} employee;

• The salayy structure contains a member named allowance, which itself is a structure with three members.

• The members contained in the inner structure namely da, hra and cca can be reffered as

employee.allowance.da;

employee.allowance.hra;

employee.allowance.cca;

• A inner-most member in a nested- structure can be accessed by chaining all the concerned structures variables with member using dot operator.

61

10.12 STRUCTURES & FUNCTIONS

There are 3 methods to transferred structure from one function to another.

1. Pass each member of structure as an actual argument of the function call. The actual arguments are then treated independently like ordinary variables. This is the most elementary method and becomes unmanageable and inefficient when the structure size is large.

2. Passing of a copy of the entire structure to the called function. Since the function is working on a copy of the structure, any changes to structure members within the function are not reflected in the original structure. Therefore the necessary for the function to return the entire structure back to the calling function.

3. Using pointers to pass the structure as an argument.

The general format of sending a copy of a structure to the called function is

function_name(structure_variable_name);

The called function format data_type

function_name(struct_variable_name) {

………….

………….

return(expression);

} Note

1. The called function must be declared for its type, appropriate to the data type it is expected to return.

2. The structure variable used as the actual argument and the corresponding formal parameter in the called function must be of the same struct type.

62

3. The return statement is necessary only when the function is returning some data back to the calling function. The

expression may be any simple variable or structure variable or an expression using simple variables

4. When a function returns a structure, it must be assigned to a structure of identical type in the calling function.

5. The called functions must be declared in the calling function appropriately.

Example

#include<stdio.h>

#include<conio.h>

/* structure is defined above all functions so it is global. */

struct student {

char name[20];

int roll_no;

int marks;

};

void print_struct(struct student stu);

void main() {

struct student stu = {"George", 10, 69};

print_struct(stu);

return 0;

}

void print_struct(struct student stu) {

printf("Name: %s\n", stu.name);

printf("Roll no: %d\n", stu.roll_no);

printf("Marks: %d\n", stu.marks);

printf("\n");

}

63

10.13 UNIONS

A union is a special data type available in C that allows to store different data types in the same memory location.

We can define a union with many members, but only one member can contain a value at any given time.

Unions provide an efficient way of using the same memory location for multiple- purpose.

Defining a Union union [union tag]

{

member definition;

member definition;

...

member definition;

} [one or more union variables];

The union tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition.

At the end of the union's definition, before the final semicolon, you can specify one or more union variables but it is optional.

Example

union Data {

int i;

float f;

char str[20];

} data;

A variable of Data type can store an integer, a floating-point number, or a string of characters.

64

It means a single variable, i.e., same memory location, can be used to store multiple types of data.

We can use any built-in or user defined data types inside a union based on your requirement.

The memory occupied by a union will be large enough to hold the largest member of the union.

Example

Data type will occupy 20 bytes of memory space because this is the maximum space which can be occupied by a character string.

Accessing Union Members

To access any member of a union, we use the member access operator (.).

The member access operator is coded as a period between the union variable name and the union member that we wish to access.

The keyword union to define variables of union type.

#include <stdio.h>

#include <string.h>

union Data {

int i;

float f;

char str[20];

};

int main( ) {

union Data data;

data.i = 10;

data.f = 220.5;

strcpy( data.str, "C Programming");

printf( "data.i : %d\n", data.i);

printf( "data.f : %f\n", data.f);

printf( "data.str : %s\n", data.str);

return 0;

}

Output: data.str : C Programming

65

10.14 BIT FIELDS

A bit field is a set of adjacent bits whose size can be from 1 to 16 bits length.

A word can therefore be divided into a number of bit fields.

The name and size of bit fields are defined using structure.

Syntax

struct tag-name {

data-type name:bit-length;

data-type name:bit-length;

………..

………..

data-type name:bit-length;

};

The data type is either signed int or unsigned int and the bit-length is the no. of bits used for a specified name.

A signed bit field should have at least 2 bits(one bit for sign).

The field name is followed by a colon.

The bit-length is decided by the range of value to be stored.

The largest value that can be stored is 2n-, where n is bit-length.

The internal representation of bit fields is machine dependent.

It depends on the size of int and ordering of bits.

15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

name n ………. name2 name1

66

Note

1. The first field always starts with the first bit of the word.

2. A bit field cannot overlap integer boundaries. Ie. The sum of lengths of all the fields in a structure should not be more than the size of a word. In case, it is more, the overlapping field is automatically forced to the beginning of the next word.

3. There can be unnamed fields declared with size.

4. There can be unused bits in the word.

5. We cannot take the address of a bit field variable. This means we cannot use scanf() function to read values into bit fields. We can neither use pointer to access the bit fields.

6. Bit fields cannot be arrayed.

7. Bit fields should be assigned values that are within the range of their size.. If we try to assign larger values, behaviour would be unpredicted.

Example

#include <stdio.h>

#include <string.h>

struct {

unsigned int age : 3;

} Age;

int main( ) {

Age.age = 4;

printf( "Sizeof( Age ) : %d\n", sizeof(Age) );

printf( "Age.age : %d\n", Age.age );

Age.age = 7;

printf( "Age.age : %d\n", Age.age );

Age.age = 8;

printf( "Age.age : %d\n", Age.age );

return 0;

}

67

Dokumen terkait