0% found this document useful (0 votes)
7 views17 pages

FCS_Module-5_Notes[Structure & Uinx]

The document provides an overview of structures in C programming, detailing their declaration, initialization, and usage, including examples for accessing structure members and using arrays of structures. It also covers nested structures, pointers to structures, self-referential structures, lookup tables, typedefs, and unions, highlighting the differences between structures and unions. The content is aimed at enhancing understanding of data organization and manipulation in C.

Uploaded by

daksh.yagya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views17 pages

FCS_Module-5_Notes[Structure & Uinx]

The document provides an overview of structures in C programming, detailing their declaration, initialization, and usage, including examples for accessing structure members and using arrays of structures. It also covers nested structures, pointers to structures, self-referential structures, lookup tables, typedefs, and unions, highlighting the differences between structures and unions. The content is aimed at enhancing understanding of data organization and manipulation in C.

Uploaded by

daksh.yagya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Module-5: STRUCTURES AND UNIX SYSTEM INTERFACE

Structure: - Structure is a collection of one or more variables of same or different data types
grouped to gather under a single name for easy handling.
Structure is a user defined data type that can store related information about an entity.
Structure is nothing but records about a particular entity.

Declaration of a Structure :- A structure is declared using the keyword struct followed by


structure name and variables are declared within a structure
The structure is usually declared before the main( ) function.
Syntax : -
struct structure_name
{
datatype member 1;
datatype member 2;
datatype member 3;
…………………..
…………………..
datatype member n;
};
Example :-
struct employee
{
int emp_no;
char name[20];
int age;
float emp_sal;
};

Initialization of structure: - A structure initialization is done after the declaration of the


structure
Syntax: -
struct structure_name structure_variable _name;
Example :-
struct employee emp1;
Accessing structure members :- A structure uses a .(dot) [Member Access Operator] to access
any member of the structure.
Example :-
emp1.emp_no =12345;

Dr Santhosh Kumar S, Jain University 1


Module-5: STRUCTURES AND UNIX SYSTEM INTERFACE

Initialization of structure variables :-


struct employee
{
int emp_no;
char name[20];
int age;
float emp_sal;
} emp1={65421, “Hari”,29,25000.00};

The order of values enclosed in the braces must match the order of members in the structure
definition.
/* C program to read and print the details of employee using structures –static allocation
of variables */
#include<stdio.h>
#include<string.h>
struct employee
{
int emp_no;
char empname[20];
int age;
float emp_sal;
};
void main()
{
struct employee emp1;
emp1.emp_no = 65421;
strcpy(emp1.empname,"Hari");
emp1.age=29;
emp1.emp_sal=25000.00;
printf("Employee Number=%d\n",emp1.emp_no);
printf("Employee Name=%s\n",emp1.empname);
printf("Employee Age=%d\n",emp1.age);
printf("Employee Salary=%f\n",emp1.emp_sal);
}

/* C program to read and print the details of employee using structures –run time allocation
of variables */
#include<stdio.h>
#include<string.h>
struct employee
{
int emp_no;
char empname[20];
int age;
float emp_sal;
};

Dr Santhosh Kumar S, Jain University 2


Module-5: STRUCTURES AND UNIX SYSTEM INTERFACE

void main()
{
struct employee emp1;
printf("Enter Employee Number:");
scanf("%d",&emp1.emp_no);
printf("Enter Employee Name:");
scanf("%s",emp1.empname);
printf("Enter Employee age:");
scanf("%d",&emp1.age);
printf("Enter Employee salary:");
scanf("%f",&emp1.emp_sal);
printf("Employee Number=%d\n",emp1.emp_no);
printf("Employee Name=%s\n",emp1.empname);
printf("Employee Age=%d\n",emp1.age);
printf("Employee Salary=%f\n",emp1.emp_sal);
}

/* C Program to find Sum of Two Complex Numbers*/

#include<stdio.h>
struct complex
{
int real;
int img;
};

void main()
{
struct complex a,b,c;
printf("Enter the First Complex Number\n");
printf("Enter the real part:");
scanf("%d",&a.real);
printf("Enter the imaginary part:");
scanf("%d",&a.img);
printf("Enter the Second Complex Number\n");
printf("Enter the real part:");
scanf("%d",&b.real);
printf("Enter the imaginary part:");
scanf("%d",&b.img);
c.real=a.real+b.real;
c.img=a.img+b.img;
if(c.img>=0)
printf("Sum of two Complex Number = %d+i%d\n",c.real,c.img);
else
printf("Sum of two Complex Number = %d %di\n",c.real,c.img);
}

Dr Santhosh Kumar S, Jain University 3


Module-5: STRUCTURES AND UNIX SYSTEM INTERFACE

Array of Structures:-
An array whose elements are of type structure is called array of structure.
It is generally useful when we need multiple structure variables in the program.
if we want to store the data of 100 employees we would require 100 structure variables from
emp1 to emp100 which is definitely impractical the better approach would be to use the array
of structures.
/* C program to illustrate array of structures */

#include<stdio.h>
#include<string.h>
struct employee
{
int emp_no;
char empname[20];
int age;
float emp_sal;
};
void main()
{
struct employee emp1[20];
int n,i;
printf("Enter the number of employee entries\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the details of employee %d\n",i+1);
printf("Enter Employee Number:");
scanf("%d",&emp1[i].emp_no);
printf("Enter Employee Name:");
scanf("%s",emp1[i].empname);
printf("Enter Employee age:");
scanf("%d",&emp1[i].age);
printf("Enter Employee salary:");
scanf("%f",&emp1[i].emp_sal);
}
printf("\nEMP_NO\t EMP_NAME\t EMP_AGE\t\t EMP_SALARY \n");
for(i=0;i<n;i++)
{
printf("%d\t%s\t%d\t%f\n",emp1[i].emp_no,emp1[i].empname,emp1[i].age,emp1[i].e
mp_sal);
}
}

Dr Santhosh Kumar S, Jain University 4


Module-5: STRUCTURES AND UNIX SYSTEM INTERFACE

Nested Structures :- A nested structure is a structure that contains another structure as its
member.
Syntax :-
struct structure_name1
{
datatype member 1;
datatype member 2;
};
struct structure_name2
{
datatype member 1;
datatype member 2;
struct structure_name1 var1;
};

/* C program to demonstrate nested structures */


#include<stdio.h>
struct stud_dob
{
int day;
int month;
int year;
};

struct student
{
int rollno;
char sname[20];
struct stud_dob date;
};

void main()
{
struct student s;
printf("Enter Student Rollno :");
scanf("%d",&s.rollno);
printf("Enter Student Name :");
scanf("%s",s.sname);
printf("Enter date of birth as day month year:");
scanf("%d%d%d",&s.date.day,&s.date.month,&s.date.year);
printf("Student Details are\n");
printf("Student Rollno = %d\n",s.rollno);
printf("Student Name=%s",s.sname);
printf("Student DOB= %d-%d-%d\n", s.date.day, s.date.month, s.date.year);
}

Dr Santhosh Kumar S, Jain University 5


Module-5: STRUCTURES AND UNIX SYSTEM INTERFACE

Structures and Functions :- Structures can be passed to functions and returned from it. We can
also pass structures using call by value and call by reference methods. A function in C may also return
a struct data type.
Passing structures to functions can be done in the following ways
– Passing individual members
– Passing entire structure or structure variable.

Passing Individual Members :-


while invoking the function from main( ) in the place of actual arguments we can pass the
structure member as an argument.
#include<stdio.h>
void add(int x,int y);
struct addition
{
int a;
int b;
};
void main()
{
struct addition sum;
printf(" Enter two numbers\n");
scanf("%d%d",&sum.a,&sum.b);
add(sum.a,sum.b);
}
void add(int x,int y)
{
int res;
res=x+y;
printf("Resultant=%d\n",res);
}

Passing Entire structure or structure variable :-while invoking the function instead of
passing the individual members the entire structure, i.e. the structure variable is passed as a
parameter to the function.

#include<stdio.h>
struct addition
{
int a;
int b;
};
void add(struct addition sum);

void main()
{
struct addition sum;
printf(" Enter two numbers\n");
scanf("%d%d",&sum.a,&sum.b);
add(sum);

Dr Santhosh Kumar S, Jain University 6


Module-5: STRUCTURES AND UNIX SYSTEM INTERFACE

}
void add(struct addition sum)
{
int res;
res=sum.a+sum.b;
printf("Resultant=%d\n",res);
}

Pointer of Structures:
A structure pointer is defined as the pointer which points to the address of the memory block that
stores a structure known as the structure pointer.
Accessing the Structure Member with the Help of Pointers
There are two ways to access the members of the structure with the help of a structure pointer:
1. With the help of (*) asterisk or indirection operator and (.) dot operator.
2. With the help of ( -> ) Arrow operator.
To access the structure members using the structure pointer with the help of the dot operator.

#include <stdio.h>
#include <string.h>
struct Student {
int roll_no;
char name[30];
char branch[40];
int batch;
};
int main()
{
struct Student s1;
struct Student* ptr = &s1;

s1.roll_no = 27;
strcpy(s1.name, "Kamlesh Joshi");
strcpy(s1.branch, "Computer Science And Engineering");
s1.batch = 2019;

printf("Roll Number: %d\n", (*ptr).roll_no);


printf("Name: %s\n", (*ptr).name);
printf("Branch: %s\n", (*ptr).branch);
printf("Batch: %d", (*ptr).batch);

return 0;
}

Dr Santhosh Kumar S, Jain University 7


Module-5: STRUCTURES AND UNIX SYSTEM INTERFACE

To access the structure members using the structure pointer with the help of the 1. Arrow
operator.
#include <stdio.h>
#include <string.h>
struct Student {
int roll_no;
char name[30];
char branch[40];
int batch;
};
struct Student s, *ptr;
int main()
{
ptr = &s;
// Taking inputs
printf("Enter the Roll Number of Student\n");
scanf("%d", &ptr->roll_no);
printf("Enter Name of Student\n");
scanf("%s", &ptr->name);
printf("Enter Branch of Student\n");
scanf("%s", &ptr->branch);
printf("Enter batch of Student\n");
scanf("%d", &ptr->batch);

printf("\nStudent details are: \n");

printf("Roll No: %d\n", ptr->roll_no);


printf("Name: %s\n", ptr->name);
printf("Branch: %s\n", ptr->branch);
printf("Batch: %d\n", ptr->batch);

return 0;
}

Self-referential Structures:
It is a structure that points to the same type of structure. It contains one or more pointers that
ultimately point to the same structure.
o The self-referential structure is widely used in dynamic data structures such as trees,
linked lists, etc.
o In this type of structure, the object of the same structure points to the same data structure
and refers to the data types of the same structure.
o It can have one or more pointers pointing to the same type of structure as their member

Dr Santhosh Kumar S, Jain University 8


Module-5: STRUCTURES AND UNIX SYSTEM INTERFACE

Syntax:
struct node {
int data1;
char data2;
struct node* link;
};

#include <stdio.h>
struct mystruct{
int a;
struct mystruct *b;
};

int main(){
struct mystruct x = {10, NULL}, y = {20, NULL}, z = {30, NULL};
struct mystruct * p1, *p2, *p3;
p1 = &x;
p2 = &y;
p3 = &z;
x.b = p2;
y.b = p3;
printf("Address of x: %d a: %d Address of next: %d\n", p1, x.a, x.b);
printf("Address of y: %d a: %d Address of next: %d\n", p2, y.a, y.b);
printf("Address of z: %d a: %d Address of next: %d\n", p3, z.a, z.b);
return 0;
}

Table look up:


Lookup tables (LUT) in C are arrays populated with certain pre-computed values. Lookup tables
help avoid performing a lot of calculations in a program.
Instead of lengthy nested if-else statements or switch statements, one can use Lookup tables to
enhance the efficiency of a C program.
Instead of frequent calls to the square() function, for each value of the array index we can declare
an array to store the squares of numbers and access the computed square directly from the index
using LUT.
#include <stdio.h>
int main(){
int squares[5] = {1, 4, 9, 16, 25};
for (int i = 0; i <= 4; i++){
printf("No: %d \tSquare(%d): %d\n", i+1, i+1, squares[i]);
}
return 0;
}

Dr Santhosh Kumar S, Jain University 9


Module-5: STRUCTURES AND UNIX SYSTEM INTERFACE

Typedef:
• The typedef keyword gives a meaningful name to the existing data type which helps other
users to understand the program more easily.
• It can be used with structures to increase code readability and we don’t have to type struct
repeatedly.
• The typedef keyword can also be used with pointers to declare multiple pointers in a single
statement.
• It can be used with arrays to declare any number of variables.
#include <stdio.h>
#include <string.h>

// using typedef to define an alias for structure


typedef struct students {
char name[50];
char branch[50];
int ID_no;
} stu;

int main()
{
stu st;
strcpy(st.name, "Kamlesh Joshi");
strcpy(st.branch, "Computer Science And Engineering");
st.ID_no = 108;

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


printf("Branch: %s\n", st.branch);
printf("ID_no: %d\n", st.ID_no);
return 0;
}

Union:- 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.
Syntax for declaring a union is same as that of declaring a structure except the keyword struct.
union union_name {
datatype field_name;
datatype field_name;
// more variables
};

Dr Santhosh Kumar S, Jain University 10


Module-5: STRUCTURES AND UNIX SYSTEM INTERFACE

Difference between Structure and Union


Structure Union
The Keyword struct is used to define The keyword union is used to
Keyword
the Structure define a union.
when a variable is associated witha
When a variable is associated with a
union, the compiler allocates the
structure, the compiler allocates the
memory by considering the size of
Size memory for each member. The size of
the largest memory. So, size of
structure is greater than or equal to the
union is equal to the size of largest
sum of sizes of its members.
member.
Each member within a structure is
Memory allocated is shared by
Memory assigned unique storage area of
individual members of union.
location.
Altering the value of a member will Altering the value of any of the
Value
not affect other members of the member will alter other member
Altering
structure. values.
Accessing Individual member can be accessed at Only one member can be accessed
members a time. at a time.
Initialization Several members of a structure can Only the first member of a union
of Members initialize at once. can be initialized.

#include <stdio.h>
struct store
{
double price;
union
{
struct{
char *title;
char *author;
int number_pages;
} book;

struct {
int color;
int size;
char *design;
} shirt;
}item;
};
int main()
{
struct store s;
s.item.book.title = "C programming";
s.item.book.author = "John";
s.item.book.number_pages = 189;
printf("Size is %ld", sizeof(s));
return 0;
}

Dr Santhosh Kumar S, Jain University 11


Module-5: STRUCTURES AND UNIX SYSTEM INTERFACE

Bit-fields:
In addition to declarators for members of a structure or union, a structure declarator can also be a
specified number of bits, called a " bit field.
Bit field are used to specify the size (in bits) of the structure and union members .
Need of Bit Fields in C
• Reduces memory consumption.
• To make our program more efficient and flexible.
• Easy to Implement.

Syntax of C Bit Fields:


struct
{
data_type member_name : width_of_bit-field;
};

Applications of C Bit Fields


• If storage is limited, we can go for bit-field.
• When devices transmit status or information encoded into multiple bits for this type of
situation bit-field is most efficient.
• Encryption routines need to access the bits within a byte in that situation bit-field is quite
useful.
#include <stdio.h>
struct date {
// d has value between 0 and 31, so 5 bits are sufficient
int d : 5;
// m has value between 0 and 15, so 4 bits are sufficient
int m : 4;
int y;
};

int main()
{
printf("Size of date is %lu bytes\n", sizeof(struct date));
struct date dt = { 31, 12, 2014 };
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
return 0;
}

Dr Santhosh Kumar S, Jain University 12


Module-5: STRUCTURES AND UNIX SYSTEM INTERFACE

File Handling in C:
File handling in C enables us to create, update, read, and delete the files stored on the local file
system through our C program. The following operations can be performed on a file.
o Creation of the new file
o Opening an existing file
o Reading from the file
o Writing to the file
o Deleting the file
File Pointer in C
A file pointer is a reference to a particular position in the opened file. It is used in file handling to
perform all file operations such as read, write, close, etc. FILE macro is used to declare the file
pointer variable. The FILE macro is defined inside <stdio.h> header file.
Syntax of File Pointer
FILE* pointer_name;

Functions for file handling:


There are many functions in the C library to open, read, write, search and close the file. A list of
file functions is given below:

No. Function Description

1 fopen() opens new or existing file

2 fprintf() write data into the file

3 fscanf() reads data from the file

4 fputc() writes a character into the file

5 fgetc() reads a character from file

6 fclose() closes the file

7 fseek() sets the file pointer to given position

8 fputw() writes an integer to file

9 fgetw() reads an integer from file

10 ftell() returns current position

11 rewind() sets the file pointer to the beginning of the file

Dr Santhosh Kumar S, Jain University 13


Module-5: STRUCTURES AND UNIX SYSTEM INTERFACE

The fopen() function is used to open a file. The syntax of the fopen() is given below.
1. FILE *fopen( const char * filename, const char * mode );
#include<stdio.h>
void main( )
{
FILE *fp ;
char ch ;
fp = fopen("file_handle.c","r") ;
while ( 1 )
{
ch = fgetc ( fp ) ;
if ( ch == EOF )
break ;
printf("%c",ch) ;
}
fclose (fp ) ;
}

2. The fclose() function is used to close a file. The file must be closed after performing all the
operations on it. The syntax of fclose() function is given below:
int fclose( FILE *fp );

Example: Program to Create a File, Write in it, And Close the File
#include <stdio.h>
#include <string.h>
int main()
{
FILE* filePointer;
char dataToBeWritten[50] = " A Computer " Science Portal ";

filePointer = fopen("GfgTest.c", "w");

if (filePointer == NULL) {
printf("GfgTest.c file failed to open.");
}
else {
printf("The file is now opened.\n");
if (strlen(dataToBeWritten) > 0) {
fputs(dataToBeWritten, filePointer);
fputs("\n", filePointer);
}
fclose(filePointer);
printf("Data successfully written in file " "GfgTest.c\n");
printf("The file is now closed.");
}
return 0;
}

Dr Santhosh Kumar S, Jain University 14


Module-5: STRUCTURES AND UNIX SYSTEM INTERFACE

fseek():
To access a particular record inside a file that is at a specific position, so we need to loop
through all the records before it to get the record. Doing this will waste a lot of memory
and operational time. To reduce memory consumption and operational time we can
use fseek() .
It provides an easier way to get to the required data. fseek() function in C seeks the cursor
to the given record in the file.
Syntax for fseek()
int fseek(FILE *ptr, long int offset, int pos);
// C Program to demonstrate the use of fseek() in C
#include <stdio.h>
int main()
{
FILE* fp;
fp = fopen("test.txt", "r");

// Moving pointer to end


fseek(fp, 0, SEEK_END);

// Printing position of pointer


printf("%ld", ftell(fp));
return 0;
}

rewind():
The rewind() function is used to bring the file pointer to the beginning of the file.
It can be used in place of fseek() when we want the file pointer at the start.
Syntax of rewind():
rewind (file_pointer);

// C program to illustrate the use of rewind


#include <stdio.h>
int main()
{
FILE* fptr;
fptr = fopen("file.txt", "w+");
fprintf(fptr, "hello\n");
// using rewind()
rewind(fptr);
// reading from file
char buf[50];
fscanf(fptr, "%[^\n]s", buf);
printf("%s", buf);

Dr Santhosh Kumar S, Jain University 15


Module-5: STRUCTURES AND UNIX SYSTEM INTERFACE

return 0;
}

Preprocessor Directives
Preprocessor Directives:-Preprocessor is a program which is invoked by the compiler before
the compilation of the user written program
–The declaration of preprocessor statements always begin with # symbol
–These statements are usually placed before the main( ) function.
Types of Preprocessors:-
–Macros
–File Inclusion
–Conditional compilation
–Other directives
Macros:-These are the piece of code in the program which is given some name.
• Whenever the name is encountered by the compiler in the program , the compiler replaces the
name with the actual piece of code.
• The “#define” directive is used to define a macro.

/* C program to demonstrate macros */


# include<stdio.h>
# define pi 3.142
void main()
{
float r,area;
printf("Enter the value of radius\n");
scanf("%f",&r);
area=pi*r*r;
printf("Area of circle = %f\n",area);
}

/*C Program that finds the addition of two squared numbers, by defining macro for
Square(x).*/

#include <stdio.h>
#define square(x) (x*x)
void main( )
{
int n1, n2, sum;
printf(“Enter two numbers”);
scanf(“%d%d”, &n1, &n2);
sum = square(n1) + square(n2);
printf(“Sum of two squared numbers = %d”, sum);
}

File Inclusion:-This type of preprocessor directive tells the compiler to include a file in the
source code program

Dr Santhosh Kumar S, Jain University 16


Module-5: STRUCTURES AND UNIX SYSTEM INTERFACE

These files contains the definition of the predefined functions like printf( ), scanf( ), etc.
Different functions are declared in different header files.
/* C program to demonstrate file inclusion */
#include<stdio.h>
#include<math.h>
void main()
{
int num;
float res;
printf("Enter a number\n");
scanf("%d",&num);
res=sqrt(num);
printf("Squareroot of %d = %f\n",num,res);
}
Conditional Compilation: -these are the type of directives that helps to compile a specific
portion of the program or to skip a specific part of the program based on some conditions.
Some of the conditional compilation directives are
– #ifdef, #ifndef, #if, #else

/* C program to demonstrate use of #ifdef*/


#include<stdio.h>
#define age 18
void main()
{
#ifdef age
printf("The person is eligible to vote");
#endif
}
/* C program to demonstrate use of #else*/
#include<stdio.h>
#define age 21
void main()
{ #ifdefage<=18
printf("The person is not eligible to vote");
#else
printf("The person is eligible to vote");
#endif
}

Other Directives:-Apart from the above directive there are two more directives which are not
commonly used

#undef directive:-this directive is used to undefined a value which was declare using the
#define directive

#pragma directive:-this directive is used in parallel programming (thread programming)


which is a major concept of operating system.

Dr Santhosh Kumar S, Jain University 17

You might also like