Professional Documents
Culture Documents
Updated CCP-unit 4
Updated CCP-unit 4
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
Syntax of structure
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeber;
}; // Don't forget the semicolon }; in the ending line.
struct person
{
char name[50];
int citNo;
float salary;
};
This declaration above creates the derived data type struct person.
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;
}
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.
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 };
There are two types of operators used for accessing members of a structure.
1. Member operator(.)
2. Structure pointer operator(->)
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.
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);
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.
5
for(i=0;i<3;i++)
{
printf("\nEnter details of %d Employee",i+1);
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("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 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.
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.
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:
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.
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.
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.
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
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
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
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);
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.
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);
function to read strings from a file, but it stops reading after encountering the first space character.
9) rewind() function is used to move file pointer position to the beginning of the file.
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.
15
11) ftell() function is used to get current position of the file pointer. The value is count from the beginning of the
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.
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;
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;
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.
3 No such process
5 I/O error
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.
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:
Disadvantages of Pointer
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:
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>
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.
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:
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;
#include <stdio.h>
int main()
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