Sei sulla pagina 1di 18

UNIT-4

STRUCTURE
C Structure is a collection of different data types which are grouped together and
each element in a C structure is called member.

Example:
Structures are used to represent a record. Suppose you want to keep track of
your books in a library. You might want to track the following attributes about
each book −
 Title
 Author
 Subject
 Book ID
Defining a Structure
To define a structure, you must use the struct statement. The struct statement
defines a new data type, with more than one member. The format of the struct
statement is as follows −
struct [structure tag]
{
member definition;
member definition;
...
member definition;
} [one or more structure variables];

The structure 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 structure's definition, before the final semicolon, you can specify one
or more structure variables but it is optional.

struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
} book;

Accessing Structure Members


To access any member of a structure, we use the member access operator (.).
The member access operator is coded as a period between the structure variable
name and the structure member that we wish to access. You would use the
keyword struct to define variables of structure type. The following example
shows how to use a structure in a program –

#include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( )
{
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "Topics in Algebra");
strcpy( Book1.author, "I N Herstein");
strcpy( Book1.subject, "Mathematics");
Book1.book_id = 6495407;

/* book 2 specification */
strcpy( Book2.title, "Mechanics");
strcpy( Book2.author, "Duraipandian");
strcpy( Book2.subject, "Mathematics");
Book2.book_id = 6495700;

/* print Book1 info */


printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n", Book1.subject);
printf( "Book 1 book_id : %d\n", Book1.book_id);
/* print Book2 info */
printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 subject : %s\n", Book2.subject);
printf( "Book 2 book_id : %d\n", Book2.book_id);
return 0;
}
When the above code is compiled and executed, it produces the following result −
Book 1 title : Topics in Algebra
Book 1 author : I N Herstein
Book 1 subject : Mathematics
Book 1 book_id : 6495407
Book 2 title : Mechanics
Book 2 author : Duraipandian
Book 2 subject : Mathematics
Book 2 book_id : 6495700
Passing Structures as Function Arguments
We can pass a structure as a function argument in the same way as we pass any
other variable or pointer.
#include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
/* function declaration */
void printBook( struct Books book );

int main( )
{
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "Topics in Algebra");
strcpy( Book1.author, "I N Herstein");
strcpy( Book1.subject, "Mathematics");
Book1.book_id = 6495407;

/* book 2 specification */
strcpy( Book2.title, "Mechanics");
strcpy( Book2.author, "Duraipandian");
strcpy( Book2.subject, "Mathematics");
Book2.book_id = 6495700;

return 0;
}
void printBook( struct Books book )
{
printf( "Book title : %s\n", book.title);
printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);
}
When the above code is compiled and executed, it produces the following result −
Book title : Topics in Algebra
Book author : I N Herstein
Book subject : Mathematics
Book book_id : 6495407
Book title : Mechanics
Book author : Duraipandian
Book subject : Mathematics
Book book_id : 6495700
Pointers to Structures
We can define pointers to structures in the same way as you define pointer to
any other variable −
struct Books *struct_pointer;
Now, you can store the address of a structure variable in the above defined
pointer variable. To find the address of a structure variable, place the '&';
operator before the structure's name as follows −
struct_pointer = &Book1;
To access the members of a structure using a pointer to that structure, you
must use the → operator as follows −
struct_pointer->title;
Let us re-write the above example using structure pointer.
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};

/* function declaration */
void printBook( struct Books *book );
int main( )
{
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */

/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;

/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;

/* print Book1 info by passing address of Book1 */


printBook( &Book1 );
/* print Book2 info by passing address of Book2 */
printBook( &Book2 );
return 0;
}

void printBook( struct Books *book )


{
printf( "Book title : %s\n", book->title);
printf( "Book author : %s\n", book->author);
printf( "Book subject : %s\n", book->subject);
printf( "Book book_id : %d\n", book->book_id);
}
When the above code is compiled and executed, it produces the following result −
Book title : C Programming
Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407
Book title : Telecom Billing
Book author : Zara Ali
Book subject : Telecom Billing Tutorial
Book book_id : 6495700

Structure variable declaration


When a structure is defined, it creates a user-defined type but, no storage or
memory is allocated.

Accessing members of a structure


There are two types of operators used for accessing members of a structure.
1. Member operator(.)
2. Structure pointer operator(->)
3. Any member of a structure can be accessed as:
structure_variable_name.member_name

Example of structure
Write a C program to add two distances entered by user. Measurement of
distance should be in inch and feet. (Note: 12 inches = 1 foot)
#include <stdio.h>
struct Distance
{
int feet;
float inch;
} dist1, dist2, sum;

int main()
{
printf("1st distance\n");

// Input of feet for structure variable dist1


printf("Enter feet: ");
scanf("%d", &dist1.feet);

// Input of inch for structure variable dist1


printf("Enter inch: ");
scanf("%f", &dist1.inch);

printf("2nd distance\n");
// Input of feet for structure variable dist2
printf("Enter feet: ");
scanf("%d", &dist2.feet);

// Input of feet for structure variable dist2


printf("Enter inch: ");
scanf("%f", &dist2.inch);

sum.feet = dist1.feet + dist2.feet;


sum.inch = dist1.inch + dist2.inch;

if (sum.inch > 12)


{
//If inch is greater than 12, changing it to feet.
++sum.feet;
sum.inch = sum.inch - 12;
}

// printing sum of distance dist1 and dist2


printf("Sum of distances = %d\'-%.1f\"", sum.feet, sum.inch);
return 0;
}
Output
1st distance
Enter feet: 12
Enter inch: 7.9
2nd distance
Enter feet: 2
Enter inch: 9.8
Sum of distances = 15'-5.7"

Structures within structures


Structures can be nested within other structures in C programming.
struct complex
{
int imag_value;
float real_value;
};

struct number
{
struct complex comp;
int real;
} num1, num2;
Suppose, you want to access imag_value for num2 structure variable then,
following structure member is used.
num2.comp.imag_value
Structure Initialization
Like any other data type, structure variable can also be initialized at compile
time.
struct Patient
{
float height;
int weight;
int age;
};
struct Patient p1 = { 180.75 , 73, 23 }; //initialization
or
struct patient p1;
p1.height = 180.75; //initialization of each member separately
p1.weight = 73;
p1.age = 23;

Array of Structure
We can also declare an array of structure. Each element of the array represents a
structure variable. Example : struct employee emp[5];
The below code define an array emp of size 5 elements. Each element of array
emp is of type employee
#include<stdio.h>
#include<conio.h>
struct employee
{
char ename[10];
int sal;
};
struct employee emp[5];
int i,j;
void ask()
{
for(i=0;i<3;i++)
{
printf("\nEnter %dst employee record\n",i+1);
printf("\nEmployee name\t");
scanf("%s",emp[i].ename);
printf("\nEnter employee salary\t");
scanf("%d",&emp[i].sal);
}
printf("\nDisplaying Employee record\n");
for(i=0;i<3;i++)
{
printf("\nEmployee name is %s",emp[i].ename);
printf("\nSlary is %d",emp[i].sal);
}
}
void main()
{
clrscr();
ask();
getch();
}

Nested Structures

Nesting of structures, is also permitted in C language.


Example :
struct student
{
char[30] name;
int age;
struct address
{
char[50] locality;
char[50] city;
int pincode;
};
};

DIFFERENCE BETWEEN C VARIABLE, C ARRAY AND C STRUCTURE:


 A normal C variable can hold only one data of one data type at a time.
 An array can hold group of data of same data type.
 A structure can hold group of data of different data types and Data types
can be int, char, float, double and long double etc.

Using normal variable Using pointer variable
Syntax: Syntax:
struct tag_name struct tag_name
{ {
data type var_name1; data type var_name1;
data type var_name2; data type var_name2;
data type var_name3; data type var_name3;
}; };
Example: Example:
struct student struct student
{ {
int mark; int mark;
char name[10]; char name[10];
float average; float average;
}; };
Declaring structure using Declaring structure using
normal variable: pointer variable:
struct student report; struct student *report, rep;
Initializing structure using
Initializing structure using pointer variable:
normal variable: struct student rep = {100,
struct student report = {100, “Mani”, 99.5};
“Mani”, 99.5}; report = &rep;
Accessing structure members Accessing structure members
using normal variable: using pointer variable:
report.mark; report -> mark;
report.name; report -> name;
report.average; report -> average;

Passing structures to a function


There are mainly two ways to pass structures to a function:
1. Passing by value
2. Passing by reference

Passing structure by value


A structure variable can be passed to the function as an argument as a normal
variable.
If structure is passed by value, changes made to the structure variable inside the
function definition does not reflect in the originally passed structure variable.
C program to create a structure student, containing name and roll and display
the information.
#include <stdio.h>
struct student
{
char name[50];
int roll;
};
void display(struct student stu);
// function prototype should be below to the structure declaration otherwise
compiler shows error
int main()
{
struct student stud;
printf("Enter student's name: ");
scanf("%s", &stud.name);
printf("Enter roll number:");
scanf("%d", &stud.roll);
display(stud); // passing structure variable stud as argument
return 0;
}
void display(struct student stu){
printf("Output\nName: %s",stu.name);
printf("\nRoll: %d",stu.roll);
}
Output
Enter student's name: Kevin Amla
Enter roll number: 149
Output
Name: Kevin Amla
Roll: 149

Passing structure by reference


The memory address of a structure variable is passed to function while passing it
by reference.
If structure is passed by reference, changes made to the structure variable inside
function definition reflects in the originally passed structure variable.
C program to add two distances (feet-inch system) and display the result without
the return statement.
#include <stdio.h>
struct distance
{
int feet;
float inch;
};
void add(struct distance d1,struct distance d2, struct distance *d3);
int main()
{
struct distance dist1, dist2, dist3;

printf("First distance\n");
printf("Enter feet: ");
scanf("%d", &dist1.feet);
printf("Enter inch: ");
scanf("%f", &dist1.inch);

printf("Second distance\n");
printf("Enter feet: ");
scanf("%d", &dist2.feet);
printf("Enter inch: ");
scanf("%f", &dist2.inch);

add(dist1, dist2, &dist3);


//passing structure variables dist1 and dist2 by value whereas passing
structure variable dist3 by reference
printf("\nSum of distances = %d\'-%.1f\"", dist3.feet, dist3.inch);
return 0;
}
void add(struct distance d1,struct distance d2, struct distance *d3)
{
//Adding distances d1 and d2 and storing it in d3
d3->feet = d1.feet + d2.feet;
d3->inch = d1.inch + d2.inch;

if (d3->inch >= 12) { /* if inch is greater or equal to 12, converting it to feet.


*/
d3->inch -= 12;
++d3->feet;
}
}
Output
First distance
Enter feet: 12
Enter inch: 6.8
Second distance
Enter feet: 5
Enter inch: 7.5

Sum of distances = 18'-2.3"

In this program, structure variables dist1 and dist2 are passed by value to
the addfunction (because value of dist1 and dist2 does not need to be displayed
in main function).
But, dist3 is passed by reference ,i.e, address of dist3 (&dist3) is passed as an
argument.
Due to this, the structure pointer variable d3 inside the add function points to
the address of dist3 from the calling main function. So, any change made to
the d3 variable is seen in dist3 variable in main function.
Bit Fields
We know that an integer occupies 2 bytes of memory which is equal to 16 bits.
Most of the time, we don’t use all the 16 bits to store the integer. So there is a
wastage of memory. To serve this purpose, C supports the concept of sharing
data items packed in a word of memory.
A bit field is a set of adjacent bits whose size can be from 1 to 16 bits in length. A
word can therefore be divided into a number of bit fields. The name and size of bit
fields are defined using a structure.

Union
A union is a special data type available in C that allows to store different data
types in the same memory location. You 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
To define a union, you must use the union statement in the same way as you
did while defining a structure. The union statement defines a new data type with
more than one member for your program. The format of the union statement is
as follows −
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. Here is the way you would define a union
type named Data having three members i, f, and str −
union Data {
int i;
float f;
char str[20];
} data;
Now, a variable of Data type can store an integer, a floating-point number, or a
string of characters. It means a single variable, i.e., same memory location, can
be used to store multiple types of data. You 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. For example, in the above example, Data type will occupy
20 bytes of memory space because this is the maximum space which can be
occupied by a character string. The following example displays the total memory
size occupied by the above union −
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};

int main( ) {
union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
return 0;
}

When the above code is compiled and executed, it produces the following result −
Memory size occupied by data : 20

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. You would use the
keyword union to define variables of union type. The following example shows
how to use unions in a program −
#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;
}
When the above code is compiled and executed, it produces the following result −
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
Here, we can see that the values of i and f members of union got corrupted
because the final value assigned to the variable has occupied the memory
location and this is the reason that the value of str member is getting printed
very well.
Now let's look into the same example once again where we will use one variable
at a time which is the main purpose of having unions −
#include <stdio.h>
#include <string.h>

union Data {
int i;
float f;
char str[20];
};

int main( ) {

union Data data;

data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);

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


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

return 0;
}
When the above code is compiled and executed, it produces the following result −
data.i : 10
data.f : 220.500000
data.str : C Programming

Here, all the members are getting printed very well because one member is being
used at a time.
 Below table will help you how to form a C union, declare a union,
initializing and accessing the members of the union.

Using normal variable Using pointer variable


Syntax: Syntax:
union tag_name union tag_name
{ {
data type var_name1; data type var_name1;
data type var_name2; data type var_name2;
data type var_name3; data type var_name3;
}; };
Example: Example:
union student union student
{ {
int mark; int mark;
char name[10]; char name[10];
float average; float average;
}; };
Declaring union using normal Declaring union using
variable: pointer variable:
union student report; union student *report, rep;
Initializing union using pointer
Initializing union using normal variable:
variable: union student rep = {100,
union student report = {100, “Mani”, 99.5};
“Mani”, 99.5}; report = &rep;
Accessing union members Accessing union members
using normal variable: using pointer variable:
report.mark; report -> mark;
report.name; report -> name;
report.average; report -> average;

DIFFERENCE BETWEEN STRUCTURE AND UNION IN C:


C Structure C Union
Union allocates one common storage
space for all its members.
Union finds that which of its member
Structure allocates storage space needs high storage space over other
for all its members separately. members and allocates that much space
Structure occupies higher Union occupies lower memory space over
memory space. structure.
We can access all members of We can access only one member of union
structure at a time. at a time.
Structure example: Union example:
struct student union student
{ {
int mark; int mark;
char name[6]; char name[6];
double average; double average;
}; };
For above structure, memory
allocation will be like below.
int mark – 2B For above union, only 8 bytes of memory
char name[6] – 6B will be allocated since double data type
double average – 8B will occupy maximum space of memory
Total memory allocation = 2+6+8 over other data types.
= 16 Bytes

Pointer and Arrays


When an array is declared, compiler allocates sufficient amount of memory to
contain all the elements of the array. Base address i.e address of the first element
of the array is also allocated by the compiler.

Suppose we declare an array arr,

int arr[5]={ 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two
bytes, the five elements will be stored as follows:
Here variable arr will give the base address, which is a constant pointer pointing
to the element, arr[0]. Therefore arr is containing the address of arr[0] i.e 1000. In
short, arr has two purpose - it is the name of an array and it acts as a pointer
pointing towards the first element in the array.
arr is equal to &arr[0] //by default
We can declare a pointer of type int to point to the array arr.

int *p;
p = arr;
or p = &arr[0]; //both the statements are equivalent.

Now we can access every element of array arr using p++ to move from one
element to another.

NOTE : You cannot decrement a pointer once incremented. p-- won't work.
pointer to Multidimensional Array
A multidimensional array is of form, a[i][j]. Lets see how we can make a pointer
point to such an array. As we know now, name of the array gives its base
address. In a[i][j], a will give the base address of this array, even a + 0 + 0 will
also give the base address, that is the address of a[0][0]element.
Here is the generalized form for using pointer with multidimensional arrays.

*(*(a + i) + j) is same as a[i][j]


Pointer and Character strings
Pointer can also be used to create strings. Pointer variables of char type are
treated as string.

char *str = "Hello";

This creates a string and stores its address in the pointer variable str. The
pointer str now points to the first character of the string "Hello". Another
important thing to note that string created using charpointer can be assigned a
value at runtime.

char *str;
str = "hello"; //this is Legal
The content of the string can be printed using printf() and puts().

printf("%s", str);
puts(str);
Notice that str is pointer to the string, it is also name of the string. Therefore we
do not need to use indirection operator *.
Array of Pointers
We can also have array of pointers. Pointers are very helpful in handling
character array with rows of varying length.

char *name[3] = {
"Adam",
"chris",
"Deniel"
};
//Now see same array without using pointer
char name[3][20] = {
"Adam",
"chris",
"Deniel"
};

In the second approach memory wastage is more, hence it is prefered to use


pointer in such cases.
Arrays are closely related to pointers in C programming but the important
difference between them is that, a pointer variable takes different addresses as
value whereas, in case of array it is fixed.
This can be demonstrated by an example:
#include <stdio.h>
int main()
{
char charArr[4];
int i;

for(i = 0; i < 4; ++i)


{
printf("Address of charArr[%d] = %u\n", i, &charArr[i]);
}

return 0;
}
When you run the program, the output will be:
Address of charArr[0] = 28ff44
Address of charArr[1] = 28ff45
Address of charArr[2] = 28ff46
Address of charArr[3] = 28ff47
Passing Strings to Functions
Strings are just char arrays. So, they can be passed to a function in a similar
manner as arrays.
.
#include <stdio.h>
void displayString(char str[]);

int main()
{
char str[50];
printf("Enter string: ");
gets(str);
displayString(str); // Passing string c to function.
return 0;
}
void displayString(char str[]){
printf("String Output: ");
puts(str);
}
Here, string c is passed from main() function to user-defined function
displayString(). In function declaration,str[] is the formal argument.

String handling functions


There are various string operations you can perform manually like: finding the
length of a string, concatenating (joining) two strings etc.
But, for programmer's ease, many of these library functions are already defined
under the header file <string.h>.

Potrebbero piacerti anche