You are on page 1of 30

Jyoti Chandnani

Structures and Union

Definition : Structures are user defined datatypes.


As array is a collection of elements of same datatype, structure is a collection of
elements of different datatypes including arrays and pointers.
- Each variable within the structure is called a member of the structure.
- Structure can hold any number of variables.
- Generally useful for creating databases.

Declaration of structures
Start declaring structure with the keyword struct followed by structure-name or
structure-tag and within { } define all variables of different data types.

Syntax : struct structure-name


{
Datatype var1; // structure members
Datatype var2;
Datatype var3;
};

For eg:
Struct student
{
int rollno; // 4 bytes
char name[20]; // 40 bytes
char course[20]; // 40 bytes
int marks_obtained; // 4 bytes
}; // total 88 bytes will be allocated

Note : till this time no memory is being allocated for the above structure definition.
to use above structure we need to create a structure variable.

struct student st1,st2; // creating structure variable

Another method:
struct {
int rollno;
char name[20];
char course[20];
int marks_obtained;
}st1,st2;
Jyoti Chandnani

In this case tagname is missing, but still its valid declaration. In this case two variables
allocated memory equivalent to the members of the structure.

With tagname we can declare any number of structure variables in the program.

Accessing the members of a structure


Structure members are accessed by using structure member operator (.) dot
operator, used between the structure name and the member name.
Syntax : structure name.member name;

struct coord
{
int x;
int y;
}first;

To access x and y we will write


first.x;
first.y;

Example :

Initialising structures
struct car car1 ={"xyz", 987432.50};

Example : Initialising Structures

Typedef

Variable for the structure can be declared in two ways.


1st way :
struct student record; /* for normal variable */
struct student *record; /* for pointer variable */

2nd way :
typedef struct student status;

When we use “typedef” keyword before struct <tag_name> like above, after that we
can simply use type definition “status” in the C program to declare structure variable.
Jyoti Chandnani

Now “status record” is equal to “struct student record”

typedef struct student


{
int mark [2];
char name [10];
float average;
} status;

// Structure using typedef:

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

typedef struct student


{
int id;
char name[20];
float percentage;
} status;

int main()
{
status record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
return 0;
}
Jyoti Chandnani

Structures as function arguments

Structures can be passed to functions in two ways”


- By passing entire structure
- Through pointers.

Passing entire structure by value


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

struct student
{
int id;
char name[20];
float percentage;
};

void func(struct student record);

int main()
{
struct student record;

record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;

func(record);
return 0;
}

void func(struct student record)


{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}
Jyoti Chandnani

Passing entire structure by reference


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

struct student
{
int id;
char name[20];
float percentage;
};

void func(struct student *record);

int main()
{
struct student record;

record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;

func(&record);
return 0;
}

void func(struct student *record)


{
printf(" Id is: %d \n", record->id);
printf(" Name is: %s \n", record->name);
printf(" Percentage is: %f \n", record->percentage);
}
Jyoti Chandnani

Declaring structure variable as a global


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

struct student
{
int id;
char name[20];
float percentage;
};
struct student record; // Global declaration of structure

void structure_demo();

int main()
{
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;

structure_demo();
return 0;
}

void structure_demo()
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}
Jyoti Chandnani

Declaring pointer to structure


Structure to the function can be passed by passing its address to the function it is
called pointer to the structure. To pass a pointer to a structure indirect membership
operator is used (->) to access structure member in the function.

Example :

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

struct student
{
int id;
char name[30];
float percentage;
};

int main()
{
int i;
struct student record1 = {1, "Raju", 90.5};
struct student *ptr;

ptr = &record1;

printf("Records of STUDENT1: \n");


printf(" Id is: %d \n", ptr->id);
printf(" Name is: %s \n", ptr->name);
printf(" Percentage is: %f \n\n", ptr->percentage);

return 0;
}

//Passing structure pointer to function

#include <stdio.h>

struct student
Jyoti Chandnani

int id;

char name[30];

float percentage;

};

int main()

int i;

struct student record1 = {1, "Jyoti", 90.5};

struct student *ptr;

ptr = &record1;

pointer_passing(ptr);

return 0;

pointer_passing(struct student *s)

printf("Records of STUDENT1: \n");

printf(" Id is: %d \n", s->id); // indirect membership operator

printf(" Name is: %s \n", s->name);

printf(" Percentage is: %f \n\n", s->percentage);

}
Jyoti Chandnani

Structures and Arrays


If you want to store rollnos o 100 students then we use array ,which can be declared
as :
Int rno[100];

But what if you want to store all the details of a student like rno, name, address,
age,class. Of course we will create a structure and declare all variables in it. Now to
store data of 100 students we need to create 100 structure variables, which is very
tedious to maintain.
So C provides solution to that is called Array of structures.
Syntax : struct student stu[100];

It means that stu is an array of 100 structure variables.


To access rno from above array we will accessing in following way

Stu[0].rno=1;
Stu[1].rno=2
Stu[2].rno=3;
.
.
So on…

Example :

#include <stdio.h>
//Created a array of structure here.
//structure declaration
struct Studata
{
char stuname[10];
int rno;
float per;
};

int main()
{
struct Studata s[10];// multiple structure variables
int i;
for(i=0;i<2;i++)
{
printf("\n Enter values for %d th student\n",i);
Jyoti Chandnani

printf("\n\nEnter Student Name :");


scanf("%s",s[i].stuname);

printf("\nEnter Student Rollno :");


scanf("%d",&s[i].rno);

printf("\nEnter Student per :");


scanf("%f",&s[i].per);
}

//display structure data


printf("STUDENT NAME ROLLNO PER \n");
for(i=0;i<2;i++)
{
printf("%s %d %f\n",s[i].stuname,s[i].rno,s[i].per);
}
return 0;
}
Jyoti Chandnani

Structure within structure

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

struct student_college_detail
{
int college_id;
char college_name[50];
};

struct student_detail
{
int id;
char name[20];
float percentage;
// structure within structure
struct student_college_detail clg_data;
}stu_data;

int main()
{
struct student_detail stu_data = {1, "Jyoti", 90.5, 71145,
"NTH"};
printf(" Id is: %d \n", stu_data.id);
printf(" Name is: %s \n", stu_data.name);
printf(" Percentage is: %f \n\n", stu_data.percentage);

printf(" College Id is: %d \n",


stu_data.clg_data.college_id);
printf(" College Name is: %s \n",
stu_data.clg_data.college_name);
return 0;
}

Nested Structure using pointer


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

struct student_college_detail
{
int college_id;
Jyoti Chandnani

char college_name[50];
};

struct student_detail
{
int id;
char name[20];
float percentage;
// structure within structure
struct student_college_detail clg_data;
}stu_data, *stu_data_ptr;

int main()
{
struct student_detail stu_data = {1, "Jyoti", 90.5, 71145,
"NTH"};
stu_data_ptr = &stu_data;

printf(" Id is: %d \n", stu_data_ptr->id);


printf(" Name is: %s \n", stu_data_ptr->name);
printf(" Percentage is: %f \n\n",
stu_data_ptr->percentage);

printf(" College Id is: %d \n",


stu_data_ptr->clg_data.college_id);
printf(" College Name is: %s \n",
stu_data_ptr->clg_data.college_name);

return 0;
}
Pictorial representation of memory allocation of structure
The size of alignment is mostly dependent on a processor architecture
Jyoti Chandnani

Unions
Structures and Unions are similar in all aspects but differ in the concept of storage
space.

The union variable allocates the memory space equal to the space to hold the largest
variable of union. It allows varying types of objects to share the same location.

Structure allocates storage space for all its members separately.


Whereas, Union allocates one common storage space for all its members
We can access only one member of union at a time. We can’t access all member
values at the same time in union.

Declaring Union

union union_name {
Datatype var1;
Datatype var2;
.
.
};

Eg :
union temp
{
Int x;
Char y;
double z;
};
In above case double occupies the largest memory space to store its value hence the
space allocated by above union is same as double i.e. 8 bytes.
Jyoti Chandnani

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

union student
{
char name[20];
char subject[20];
float percentage;
};

int main()
{
union student record1;
union student record2;

// assigning values to record1 union variable


strcpy(record1.name, "Raju");
strcpy(record1.subject, "Maths");
record1.percentage = 86.50;

printf("Union record1 values example\n");


printf(" Name : %s \n", record1.name);
printf(" Subject : %s \n", record1.subject);
printf(" Percentage : %f \n\n", record1.percentage);

// assigning values to record2 union variable


printf("Union record2 values example\n");
strcpy(record2.name, "Mani");
printf(" Name : %s \n", record2.name);

strcpy(record2.subject, "Physics");
printf(" Subject : %s \n", record2.subject);

record2.percentage = 99.50;
printf(" Percentage : %f \n", record2.percentage);
return 0;
}
Jyoti Chandnani

Initialising and Accessing members of an Union

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

union student
{
char name[20];
char subject[20];
float percentage;
}record;

int main()
{

strcpy(record.name, "Raju");
strcpy(record.subject, "Maths");
record.percentage = 86.50;

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


printf(" Subject : %s \n", record.subject);
printf(" Percentage : %f \n", record.percentage);
return 0;
}
Jyoti Chandnani

Getchar() and putchar()


The getchar() function
The getchar() function obtains a character from stdin. It returns the character that
was read in the form of an integer or EOF if an error occurs.
The putchar(int char) method in C is used to write a character, of unsigned char type,
to stdout. This character is passed as the parameter to this method.
Example :
#include <stdio.h>

int main (){


int i;

printf("Enter a character: ");


i = getchar();

printf("\nThe character entered is: ");


putchar(i);

return(0);
}

Buffer is temporary placeholder (variables in many programming languages) in


memory (ram/disk) on which data can be dumped and then processing can be done.
C uses a buffer to output or input variables. The buffer stores the variable that is
supposed to be taken in (input) or sent out (output) of the program. A buffer needs
to be cleared before the next input is taken in.

#include<stdio.h>
void main()
{

int x,nm;
scanf("%d",&x);
fflush(stdin);
nm=getchar();
printf("%d %c",x,nm);
}
So in-order to flush the data stored in IO buffer, we need to use fflush function.

fflush(stdin)
it is used to clear the input buffer memory. It is recommended to use before writing
scanf statement.
Jyoti Chandnani

C formatting
#include <stdio.h>
int main()
{
int pos = 14;
float data = 1.2;
printf("%*f",pos,data); // * specify the size of field
return 0;
}

#include <stdio.h>
int main()
{
char blogName[] = "Jyoti Kundnani";
printf("%s\n", blogName);
printf("%24s\n", blogName); // field size is 24
printf("%-24s\n", blogName); // left aligned
printf("%24.6s\n", blogName); // 6 characters to be displayed
printf("%-24.6s\n", blogName);// 6 character and left aligned
return 0;
}

Example :
printf("STUDENT NAME ROLLNO PER \n");
for(i=0;i<2;i++)
{
printf("%15s %5d %10.2f\n",s[i].stuname,s[i].rno,s[i].per);
}
return 0;
}

Above code will printf the output in table format.


Jyoti Chandnani

C Pre-processors
Before a C program is compiled in a compiler, source code is processed by a program
called preprocessor. This process is called pre-processing.
Commands used in preprocessor are called preprocessor directives and they begin
with “#” symbol.

Pre-processor Description
Macro #define
This is also called Symbolic constant, used to give
name to the value
Header file inclusion There are two ways of file inclusion
1. #include <file_name>-System header file
2. #include “file_name.c” -header files of your own

Example : Struct_global.c
#include <stdio.h>
struct student
{
int id;
char name[20];
float percentage;
};
struct student record; // Global declaration of structure
#include "myheader.c" // include your own file wherever needed
void structure_global(); // prototype

int main()
{
record.id=1;
strcpy(record.name, "Jyoti");
record.percentage = 98.5;
structure_global(); // calling function from myheader.c
return 0;
}

myheader.c file
//my header file
void structure_global()
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage); }
Jyoti Chandnani

C – Buffer manipulation functions


Buffer manipulation functions in C work on the address of the memory block rather
than the values inside the address.

Functions Description
memset() It is used to initialize a specified number of bytes to null or
any other value in the buffer
memcpy() It is used to copy a specified number of bytes from one
memory to another
memmove() It is used to copy a specified number of bytes from one
memory to another or to overlap on same memory.
Difference between memmove and memcpy is, overlap can
happen on memmove whereas memcpy should be done in
non-destructive way
memcmp() It is used to compare specified number of characters from
two buffers
memicmp() It is used to compare specified number of characters from
two buffers regardless of the case of the characters
memchr() It is used to locate the first occurrence of the character in the
specified string

EXAMPLE PROGRAM FOR memset() FUNCTION IN C:


memset( ) function is used to initialize specified number of bytes to null or to any
other value in the buffer.
#include <stdio.h>
#include <string.h>

int main () {
char str[30];

strcpy(str,"We are learning C Programming");


puts(str);

memset(str,’@’,10);
puts(str);

return(0);
}
Jyoti Chandnani

memcpy() : It is used to copy a specified number of bytes from one memory to


another.

#include <stdio.h>
#include <string.h>
int main()
{
// define two identical arrays
char str1[10] = "Jyoti";
char str2[10] ;
if (memcpy(str2,str1, strlen(str1)))
{
printf("Elements in str1 are copied to str2 .\n");
printf("str1 = %s\n str2 = %s \n", str1, str2);
}
else
printf("Error while coping str1 into str2.\n");
return 0;
}

memmove() : It is used to copy a specified number of bytes from one memory to


another or to overlap on same memory.

#include <stdio.h>
#include <string.h>
int main()
{
// define two identical arrays
char str1[10] = "fresh";

printf("str1 before memmove\n");


printf("str1 = %s\n ", str1);

if (memmove(str1+2,str1, strlen(str1)))
{
printf("Elements in str1 are moved/overlapped on str1.\n");
printf("str1 = %s \n", str1);
}
else
printf("Error while coping str1 into str2.\n");
return 0;
}
Jyoti Chandnani

Memchr() : It is used to locate the first occurrence of the character in the specified
string

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

int main ()
{
char *ptr;
char string[] = "Jyoti Kundnani";
ptr = (char *) memchr (string, 'i', strlen(string));
if (ptr != NULL)
printf ("character 'h' is found at " \
"position %d.\n", ptr-string+1);
else
printf ("character 'h' does not found.\n");
return 0;
}
Jyoti Chandnani

Files
When data is stored in variables , the data is lost the time you exit from program. In
programming we may want to store variable data somewhere which can be retrieved
later. To achieve this we can use file system.
File handling in C enables us to create, update, read, and delete the files stored on
the computer through our C program. The following operations can be performed on
a file.
• Opening an existing file
• Creation of the new file
• Reading from the file
• Writing to the file
• Deleting the file

File Handling Functions


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


Jyoti Chandnani

Program to open, read data from file and closing a file.


Let us understand with the help of example
// program to open a file for reading
#include<stdio.h>
void main( )
{
FILE *fp ; // file pointer to access any file
char ch ;

if((fp = fopen("arr1.c","r"))==NULL) // fopen returns a file pointer if it returns NULL


{
printf("File Does Not Exist"); // means file does not exist
exit(0); // terminates the execution of program.
}

while ( 1 )
{
ch = fgetc ( fp ) ;
if ( ch == EOF ) // file ends with end of the file marker
break ;
printf("%c",ch) ;
}
fclose (fp ) ; // after processing it closes the file stream, clears the buffer
}

FILE *fp
fp=fopen(char *filename, *mode);

mode is a string containing the desired open status.


File name must be a string of characters that provides a valid filename

The fopen function works in the following way.


• First it searches the file to be opened. (fopen())
• Then, it loads the file from the disk and place it into the buffer. (file pointer)
• It sets up a character pointer which points to the first character of the file which is
in buffer.
Why do we need a buffer at all?
Imagine how inefficient it would be to actually access the disk every time we want to
read a character from it. Every time we read something from a disk, it takes some
time for the disk drive to position the read/write head correctly. On a floppy disk
system, the drive motor has to actually start rotating the disk from a standstill
position every time the disk is accessed. If this were to be done for every character
Jyoti Chandnani

we read from the disk, it would take a long time to complete the reading operation.
This is where a buffer comes in. It would be more sensible to read the contents of
the file into the buffer while opening the file and then read the file character by
character from the buffer rather than from the disk.

Mode Description
r opens a text file in read mode
w opens a text file in write mode
a opens a text file in append mode
r+ opens a text file in read and write mode
w+ opens a text file in read and write mode
a+ opens a text file in read and append mode
Rb opens a binary file in read mode
Wb opens a binary file in write mode
Ab opens a binary file in append mode
rb+ opens a binary file in read and write mode
wb+ opens a binary file in read and write mode
ab+ opens a binary file in read and append mode

Close a File using the function fclose()


Syntax : int fclose(FILE *fp);
Example : fclose (fp ) ;

This function flushes data for stream and frees buffer and closes the stream. The
return value is 0 if the file is closed successfully or a constant EOF if an error
occurred. If this function is not given in program operating system automatically
closes the file after program termination.
Once the file is closed it cannot be used further until it is opened again.
Jyoti Chandnani

Input and output using file pointer


After opening a file, the next thing needed is the way to read and write the file.
There are several functions and macros for reading and writing the file. These
functions can be categorized according to the form and type of data read and written
on to a file. These functions are classified as:
• Character input/output functions.(fgetc and fputc)
• String input/output functions.(fgets and fputs)
• Formatted input/output functions. (fscanf and fprintf)
• Block input/output functions. fread and fwrite

Character input/output functions.


getc() : read a character from stream.(file or console)
putc() : write a character to a stream.

Syntax :
int getc(FILE *stream); -- eg : getc(fp) or getc(stdin)
int putc(int ch, FILE *stream); -- eg: putc(ch,fp) or putc(ch,stdout)

fgetc() and fputc() : C provides equivalent function to read/write characters from / to


a file.
Syntax:
int fgetc(FILE *stream); -- eg : fgetc(fp) // reading data from file pointer
int fputc(int ch, FILE *stream); -- eg: fputc(ch,fp) //writing data
to check end of file→ feof() → int feof(FILE *fp) → eg : feof(fp)
it returns 1 if end of file has been reached else 0.
Example : copy content of one file to another.

# include <stdio.h>
# include <stdlib.h>
int main( )
{
FILE *fs, *ft ;
char ch ;
fs = fopen ( "airticket.c", "r" ) ;
if ( fs == NULL )
{
puts ( "Cannot open source file" ) ;
exit (1) ;
}
ft = fopen ( "arrcopy.c", "w" ) ;
if ( ft == NULL )
{
Jyoti Chandnani

puts ( "Cannot open target file" ) ;


fclose ( fs ) ;
exit (1) ;
}
while ( 1 )
{
ch = fgetc ( fs ) ;
if ( ch == EOF )
break ;
else
fputc (ch,ft) ;
}
fclose ( fs ) ;
fclose ( ft ) ;
return 0 ;
}
Jyoti Chandnani

String input/output functions.


fgetc() function reads a character from the file, C also provides string input output
functions with the help of which we can read/write set of characters at one time.

fgets() → int fgets(char *str, int num, File *stream) → fgets(str,80,stdin)


fputs()→ char* fputs(char *str, File *stream); → fputs(str,stdout)

Interger variable num indicate the number of characters to be read


Example : read from screen and puts in file

/* Receives strings from keyboard and writes them to file */


# include <stdio.h>
# include <stdlib.h>
# include <string.h>
int main( )
{
FILE *fp ;
char s[ 80 ] ;
fp = fopen ( "myfile.txt", "w" ) ;
if ( fp == NULL )
{
puts ( "Cannot open file" ) ;
exit ( 1 ) ;
}
printf ( "\nEnter a few lines of text:\n" ) ;
while ( strlen ( gets ( s ) ) > 0 )
{
fputs ( s, fp ) ;
fputs ( "\n", fp ) ;
}
fclose ( fp ) ;
return 0 ;
}

Formatted input/output functions.


Character input output functions are not enough if file contains data in the form of
digits, float, characters and strings. Also data in some specific format wont be written
to the file. Hence C provides a set of formatted input/output functions.

fscanf() → int fscanf(FILE *fp,char *format,….); // fetch record


fprintf() → int fprintf(“FILE *fp,char *format…); // write record
Jyoti Chandnani

Both these functions return an integer indicating the number of bytes actually read
or written.
Example :
/* Read records from a file using structure */
# include <stdio.h>
# include <stdlib.h>
int main( )
{
FILE *fp ;
struct emp
{
char name[ 40 ] ;
int age ;
float bs ;
};
struct emp e ;
fp = fopen ( "EMP.DAT", "r" ) ;
if ( fp == NULL )
{
puts ( "Cannot open file" ) ;
exit ( 1 ) ;
}
while ( fscanf ( fp, "%s %d %f", e.name, &e.age, &e.bs ) != EOF )
printf ( "%s %d %f\n", e.name, e.age, e.bs ) ;
fclose ( fp ) ;
}

Block input/output functions.


fread() and fwrite() functions are commonly used to read and write binary data to
and from the file respectively. Although we can also use them with text mode too
Syntax :
fread()
fwrite()
int fread(void *buf, int num_bytes , int count , FILE *fp);
int fwrite(void *buf, int num_bytes , int count , FILE *fp);

buf is the pointer to a memory area that receives and write the data to/from a file.
Generally these functions are used to read and write array of records from or to a
file.
Jyoti Chandnani

Example :
/* Receives records from keyboard and writes them to a file in binary
mode */
# include <stdio.h>
# include <stdlib.h>
int main( )
{
FILE *fp ;
char another = 'Y' ;
struct emp
{
char name[ 40 ] ;
int age ;
float bs ;
};
struct emp e ;
fp = fopen ( "EMP.DAT", "wb" ) ;
if ( fp == NULL )
{
puts ( "Cannot open file" ) ;
exit ( 1 ) ;
}
while ( another == 'Y' )
{
printf ( "\nEnter name, age and basic salary: " ) ;
scanf ( "%s %d %f", e.name, &e.age, &e.bs ) ;
fwrite ( &e, sizeof ( e ), 1, fp ) ;
printf ( "Add another record (Y/N) " ) ;
fflush ( stdin ) ;
another = getche( ) ;
}
fclose ( fp );
return 0;
}
Jyoti Chandnani

Positioning the file pointer


To support random access file, C requires a function with the help of which the file
pointer can be positioned at any random location in the file. Such a function defined
in the standard library is discussed below :

fseek() is used to set the file position. Its prototype is :

int fseek(FILE *fp, long offset, int pos);

fp – pointer to file

offset – number of bytes to move the file pointer, counting from 0. It can be positive
or negative depending on the desired movement.

pos: from where to compute the offset.

pos has three values

SEEK_CUR(0) – beginning of the file

SEEK_SET(1) – current position

SEEK_END(2) – end of the file

fseek(fp,0,SEEK_SET); or rewind (fp);

You might also like