Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 28

UNIT -4

4.1 Structures & Unions

Structure is a collection of variables of different types under a single name. A structure can be considered as a
template used for defining a collection of variables under a single name. Structures help programmers to group
elements of different data types into a single logical unit.

For example: You want to store some information about a person: his/her name, citizenship number and salary.
You can easily create different variables name, citNo, salary to store these information separately.

However, in the future, you would want to store information about multiple persons. Now, you'd need to create
different variables for each information per person: name1, citNo1, salary1, name2, citNo2, salary2 you can
easily visualize how big and messy the code would look. Also, since no relation between the variables
(information) would exist, it's going to be a difficult task.

A better approach will be to have a collection of all related information under a single name Person, and use it for
every person. Now, the code looks much cleaner, readable and efficient as well. This collection of all related
information under a single name Person is a structure.

Structure Definition

Keyword struct is used for creating a structure.

Syntax of structure

struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeber;
}; // Don't forget the semicolon }; in the ending line.

We can create the structure for a person as mentioned above as:

struct person
{
char name[50];
int citNo;
float salary;
};

This declaration above creates the derived data type struct person.

Structure variable declaration

When a structure is defined, it creates a user-defined type but, no storage or memory is allocated. For the above
structure of a person, variable can be declared as:
1
struct person
{
char name[50];
int citNo;
float salary;
};
int main()
{
struct person person1, person2, person3[20];
return 0;
}

Another way of creating a structure variable is:

struct person
{
char name[50];
int citNo;
float salary;
} person1, person2, person3[20];

In both cases, two variables person1, person2 and an array person3 having 20 elements of type struct person are
created.

Different Ways of Declaring Structure Variable :

Way 1 : Immediately after Structure Template


struct date
{
int day;
char month[20];
int year;
}today; // 'today' is name of Structure variable

Way 2 : Declare Variables using struct Keyword


struct date
{
int day;
char month[20];
int year;
};

struct date today;

Way 3 : Declaring Multiple Structure Variables


struct Book
{
int pages;
char name[20];
int year;
}book1, book2, book3;
2
We can declare multiple variables separated by comma directly after closing curly brace.

Structure Initialization

When we declare a structure, memory is not allocated for un-initialized variable. When you first define a
structure in a file, the statement simply tells the C compiler that a structure exists, but causes no memory
allocation. Only when a structure variable is declared, memory allocation takes place.

Way 1:
struct student
{
char name[20];
int roll;
float marks;
}std1 = { "Pritesh",67,78.3 };

Way 2 : Declaring and Initializing Multiple Variables


struct student
{
char name[20];
int roll;
float marks;
}
std1 = {"Pritesh",67,78.3};
std2 = {"Don",62,71.3};

Way 3 : Initializing inside main


struct student
{
int mark1;
int mark2;
int mark3;
};
void main()
{
struct student s1 = {89,54,65};
- - - - --
- - - - --
}

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(->)

Any member of a structure can be accessed as:

structure_variable_name.member_name
3
If we want to access salary for structure variable person2. Then, it can be accessed as: person2.salary

Nested structures

 Nested structure in C is nothing but structure within structure. One structure can be declared inside other
structure as we declare structure members inside a structure.
 The structure variables can be a normal structure variable or a pointer variable to access the data. You can
learn below concepts in this section.

1. Structure within structure in C using normal variable

2. Structure within structure in C using pointer variable

1. Structure within structure in C using normal variable:

 This program explains how to use structure within structure in C using normal variable. “college’’
structure is declared inside “student” structure in this program. Both structure variables are normal
structure variables.
 Please note that members of “college” structure are accessed by 2 dot(.) operator and members of
“student” structure are accessed by single dot(.) operator.

Syntax:
struct tagname1
{
member1;
member2;
member3;
...
membern;

struct tagname2
{
member1;
member2;
member3;
...
membern;
}, var1

} var2;

#include <stdio.h>
#include <string.h>

struct college
{
int cid;
char cname[50];
};

4
struct student
{
int sid;
char name[20];
float per;
struct college cdata; // structure within structure
}sdata;

main()
{
struct student sdata = {1, "Raju", 90.5, 71145, "REVA University"};
printf(" Id is: %d \n", sdata.sid);
printf(" Name is: %s \n", sdata.name);
printf(" Percentage is: %f \n\n", sdata.per);

printf(" College Id is: %d \n", sdata.cdata.cid);


printf(" College Name is: %s \n", sdata.cdata.cname);
}

Array of Structure

Structure is collection of different data type. An object of structure represents a single record in memory, if we
want more than one record of structure type, we have to create an array of structure or object. As we know, an
array is a collection of similar type, therefore an array can be of structure type.

Syntax for declaring structure array


struct struct-name
{
datatype var1;
datatype var2;
----------
----------
datatype varN;
};
struct struct-name objname[size];

Example for declaring structure array (employee information)


#include<stdio.h>
struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};
void main()
{
int i;
struct Employee Emp[3];

5
for(i=0;i<3;i++)
{
printf("\nEnter details of %d Employee",i+1);

printf("\n\tEnter Employee Id : ");


scanf("%d",&Emp[i].Id);
printf("\n\tEnter Employee Name : ");
scanf("%s",Emp[i].Name);

printf("\n\tEnter Employee Age : ");


scanf("%d",&Emp[i].Age);
printf("\n\tEnter Employee Salary : ");
scanf("%ld",&Emp[i].Salary);
}
printf("\nDetails of Employees");
for(i=0;i<3;i++)
printf("\n%d\t%s\t%d\t%ld",Emp[i].Id,Emp[i].Name,Emp[i].Age,Emp[i].Salary);
}

Write C Program using structure to read and display the information about a student.

#include<stdio.h>

struct student
{
char name[50];
int roll;
float marks;
} s; //create object of struct student

main()
{
printf("Enter information:\n"); //Accept Name
printf("Enter name: ");
scanf("%s", s.name);

printf("Enter roll number: "); //Accept Roll Number


scanf("%d", &s.roll);

printf("Enter marks: "); //Accept Marks


scanf("%f", &s.marks);

printf("Displaying Information:\n");

printf("Name: ");
puts(s.name); //print s.name
printf("Roll number: %d\n",s.roll);
printf("Marks: %.1f\n", s.marks);
}

6
7
8
9
10
4.2 UNION
Unions are quite similar to the structures in C. Union is also a derived type as structure. Union can be
defined in same manner as structures just the keyword used in defining union in union where keyword used in
defining structure was struct.

union car{
char name[50];
int price;
};

Union variables can be created in similar manner as structure variable.

union car{
char name[50];
int price;
}c1, c2, *c3;

OR

union car {
char name[50];
int price;
};

main()
{
union car car1, car2, *car3;
}

In both cases, union variables car1, car2 and union pointer variable car3 of type union car is created.

Accessing members of an union

The member of unions can be accessed in similar manner as that structure. Suppose, we you want to access price
for union variable c1 in above example, it can be accessed as c1.price. If you want to access price for union
pointer variable c3, it can be accessed as (*c3).price or as c3->price.

Difference between union and structure

Though unions are similar to structure in so many ways, the difference between them is crucial to understand.
The primary difference can be demonstrated by this example:

1. More memory is allocated to structures than union

As seen in the above example, there is a difference in memory allocation between union and structure. The
amount of memory required to store a structure variable is the sum of memory size of all members.

11
But, the memory required to store a union variable is the memory required for the largest element of an union.

What difference does it make between structure and union?


As you know, all members of structure can be accessed at any time. But, only one member of union can be
accessed at a time in case of union and other members will contain garbage value.

2. Only one union member can be accessed at a time

In the case of structure, all of its members can be accessed at any time. But, in the case of union, only one of its
members can be accessed at a time and all other members will contain garbage values.

Difference between Structure and Union

Write a C program using union to display the total memory size occupied by the data types.

#include <stdio.h>
union Employee //defining a union
{
char name[32];
float salary;
int workerNo;
} emp1;

12
struct employee
{
char name[32];
float salary;
int workerNo;
} emp2;

int main()
{
printf("size of union = %d", sizeof(emp1));
printf("\nsize of structure = %d", sizeof(emp2));
return 0;
}

Output

size of union = 32
size of structure = 40

4.3 Formatted Input & Output, Character Input and Output Functions
Already discussed in Unit-1

4.4 FILES

A file represents a sequence of bytes on the disk where a group of related data is stored. File is created for
permanent storage of data. It is a readymade structure. In C language, we use a structure pointer of file type to
declare a file.

FILE *file_pointer_name; Ex: FILE *fp;

To use a file four essential actions should be carried out. These are,
a. Declare a file pointer variable.
b. Open a file using the fopen() function.
c. Process the file using suitable functions.
d. Close the file using the fclose() and fflush() functions

Different operations that can be performed on a file are:

Function description
 fopen() create a new file or open a existing file
 fclose() closes a file
 fgetc() reads a character from a file
 fputc() writes a character to a file
 fgets() reads string from a file
 fputs() writes a string to a file
 fscanf() reads a set of data from a file
 fprintf() writes a set of data to a file
13
 fseek() set the position to desire point
 ftell() gives current position in the file
 rewind() set the position to the beginning point

Opening a File or Creating a File

1) *fp= FILE *fopen (const char *filename, const char *mode)

fopen() function is used to open a file to perform operations such as reading, writing etc. In a C program, we
declare a file pointer and then use fopen() function. Here filename is the name of the file to be opened and mode
specifies the purpose of opening the file. Mode can be of following types,

mode description
 r: opens a text file in reading mode
 w :opens or create a text file in writing mode.
 a :opens a text file in append mode
 r+ :opens a text file in both reading and writing mode
 w+ :opens a text file in both reading and writing mode
 a+: opens a text file in both reading and writing mode

*fp is the FILE pointer (FILE *fp), which will hold the reference to the opened (or created) file.

Closing a File

2) int fclose( FILE *fp );

fclose() function is used to close an already opened file.Here fclose() function closes the file and returns zero on
success, or EOF if there is an error in closing the file. This EOF is a constant defined in the header file stdio.h.
Ex: fclose (fp);

Character / String input / output:

3) int fgetc( FILE * fp );


The fgetc() function reads a character from the input file referenced by fp. The return value is the character read,
or in case of any error, it returns EOF. Ex: fgetc(fp);

4) int fputc( int c, FILE *fp );


The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the written
character written on success otherwise EOF if there is an error. Ex: fputc(ch, fp);

14
5) int fputs (const char *string, FILE *fp)

fputs function writes string into a file pointed by fp. It returns a non-negative value on success, otherwise EOF is
returned in case of any error. In a C program, we write string into a file as below.

Ex: fputs (“some data”, fp);

6) char fgets( char string, int n, FILE *fp );

The functions fgets() reads up to n-1 characters from the input stream referenced by fp. It copies the read string
into the buffer buf, appending a null character to terminate the string. Ex: fgets(str,80, fp);

Reading and Writing from File using fprintf() and fscanf()

7) fprintf(FILE *fp, ”type specifier” , var-list);

write a string into a file.

Ex: fprintf(fp, "This is testing for fprintf...\n");

8) fscanf(FILE *fp, ”type specifier” , var-list);

function to read strings from a file, but it stops reading after encountering the first space character.

Ex: fscanf(fp, "%s", buff);

File Positioning Functions / Random Access to files of records

9) rewind() function is used to move file pointer position to the beginning of the file.

void rewind(FILE *fp)

we use rewind() as below. rewind(fp);

10) fseek() function is used to move file pointer position to the given location.
int fseek(FILE *fp, long int offset, int pos)

fp – file pointer
offset – Number of bytes/characters to be offset/moved from position/the current file pointer position.
pos – this sets the pointer position in the file.

Value pointer position


0 Beginning of file.
1 Current position
2 End of file

15
11) ftell() function is used to get current position of the file pointer. The value is count from the beginning of the
file.

long int ftell(FILE *fp)

In a C program, we use ftell() as below. ftell(fp);

Reading and Writing in a Binary File

A Binary file is similar to the text file, but it contains only large numerical data. The Opening modes are
mentioned in the table for opening modes above.

12) fread() and fwrite() functions are used to read and write is a binary file.

fwrite(data-element-to-be-written, size_of_elements, number_of_elements, pointer-to-file);

fread() is also used in the same way, with the same arguments like fwrite() function.

C program to create a file called emp.txt and store information about a person, in terms of his name, age
and salary. */

#include <stdio.h>
void main()
{
FILE *fptr;
char name[20];
int age;
float salary;

fptr = fopen ("emp.txt", "w"); /* open for writing*/

if (fptr == NULL)
{
printf("File does not exists \n");
exit(0);
}
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name = %s\n", name);
printf("Enter the age \n");
scanf("%d", &age);
fprintf(fptr, "Age = %d\n", age);
printf("Enter the salary \n");
scanf("%f", &salary);
fprintf(fptr, "Salary = %.2f\n", salary);
fclose(fptr);
}

16
$ cc pgm95.c
$ a.out
Enter the name
raj
Enter the age
40
Enter the salary
40000

C program to illustrate how a file stored on the disk and display its content */
#include <stdio.h>
#include <stdlib.h>

void main()
{
FILE *fptr;
char filename[15];
char ch;

printf("Enter the filename to be opened \n");


scanf("%s", filename);
fptr = fopen(filename, "r"); /* open the file for reading */
if (fptr == NULL)
{
printf("Cannot open file \n");
exit(0);
}
ch = fgetc(fptr);
while (ch != EOF)
{
printf ("%c", ch);
ch = fgetc(fptr);
}
fclose(fptr);
}

4.5 Error Handling in C

C language does not provide any direct support for error handling. However a few methods and variables defined
in error.h header file can be used to point out error using the return statement in a function. In C language, a
function returns -1 or NULL value in case of any error and a global variable errno is set with the error code. So
the return value can be used to check error while programming.

What is errno?

Whenever a function call is made in C language, a variable named errno is associated with it. It is a global
variable, which can be used to identify which type of error was encountered while function execution, based on
its value. Below we have the list of Error numbers and what does they mean.

errno value Error


17
1 Operation not permitted

2 No such file or directory

3 No such process

4 Interrupted system call

5 I/O error

6 No such device or address

7 Argument list too long

8 Exec format error

9 Bad file number

10 No child processes

11 Try again

12 Out of memory

13 Permission denied

The C programming language provides perror() and strerror() functions which can be used to display the text
message associated with errno.

 The perror() function displays the string you pass to it, followed by a colon, a space, and then the textual
representation of the current errno value.
 The strerror() function, defined in string.h library. which returns a pointer to the textual representation
of the current errno value.

Other ways of Error Handling

We can also use Exit Status constants in the exit() function to inform the calling function about the error. The
two constant values available for use are EXIT_SUCCESS and EXIT_FAILURE. These are nothing but macros
defined stdlib.h header file.

exit function is used to indicate exit status. Its always a good practice to exit a program with a exit status.
EXIT_SUCCESS and EXIT_FAILURE are two macro used to show exit status. In case of program coming out
after a successful operation EXIT_SUCCESS is used to show successful exit. It is defined as 0. EXIT_Failure
is used in case of any failure in the program. It is defined as -1.

18
Division by Zero Errors

There are some situation where nothing can be done to handle the error. In C language one such situation is
division by zero. All you can do is avoid doing this, because if you do so, C language is not able to understand
what happened, and gives a runtime error.

Best way to avoid this is, to check the value of the divisor before using it in the division operations. You can use
if condition, and if it is found to be zero, just display a message and return from the function.

Advantages of pointers:

 Pointers provide direct access to memory.


 Pointers allows us to return more than one value from the functions.
 Reduces the execution time of the program.
 Pointers provide a way to perform dynamic memory allocation and deallocation.

Disadvantages of Pointer

 Uninitialized pointers might cause segmentation fault.


 Dynamically allocated block needs to be freed explicitly.
 If pointers are updated with incorrect values, it might lead to memory corruption.

19
20
21
22
23
24
25
4.6 C - Command Line Arguments

It is possible to pass some values from the command line to your C programs when they are executed. These
values are called command line arguments and many times they are important for your program especially
when you want to control your program from outside instead of hard coding those values inside the code.

Syntax:

int main(int argc, char *argv[])

Here argc counts the number of arguments on the command line and argv[ ] is a pointer array which holds pointers
of type char which points to the arguments passed to the program.

The command line arguments are handled using main() function arguments where argc refers to the number of
arguments passed, and argv[] is a pointer array which points to each argument passed to the program. Following
is a simple example which checks if there is any argument supplied from the command line and take action
accordingly −

#include <stdio.h>

int main( int argc, char *argv[] ) {

if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}

When the above code is compiled and executed with single argument, it produces the following result.

$./a.out testing
The argument supplied is testing

When the above code is compiled and executed with a two arguments, it produces the following result.

$./a.out testing1 testing2


Too many arguments supplied.

When the above code is compiled and executed without passing any argument, it produces the following result.

$./a.out
One argument expected

It should be noted that argv[0] holds the name of the program itself and argv[1] is a pointer to the first command
line argument supplied, and *argv[n] is the last argument. If no arguments are supplied, argc will be one, and if
you pass one argument then argc is set at 2.

You pass all the command line arguments separated by a space, but if argument itself has a space then you can
pass such arguments by putting them inside double quotes "" or single quotes ''.
26
Properties of Command Line Arguments:

1. They are passed to main() function.


2. They are parameters/arguments supplied to the program when it is invoked.
3. They are used to control program from outside instead of hard coding those values inside the code.
4. argv[argc] is a NULL pointer.
5. argv[0] holds the name of the program.
6. argv[1] points to the first command line argument and argv[n] points last argument.

C typedef

• The typedef is a keyword that is used to provide existing data types with a new name.
• The C typedef keyword is used to redefine the name of already existing data types.
• When names of datatypes become difficult to use in programs, typedef is used with user-defined
datatypes, which behave similarly to defining an alias for commands.

• typedef existing_name alias_name;

typedef long long ll;

// C program to implement typedef

#include <stdio.h>

// defining an alias using typedef

typedef long int li;

int main()

// using typedef name to declare variable

li a = 20;

printf("%ld", a);

return 0;

typedef struct

27
• typedef can also be used with structures in the C programming language.
• A new data type can be created and used to define the structure variable.

28

You might also like