0% found this document useful (0 votes)
2 views

c Programming and Data Structures - Unit II Notes

This document covers advanced features of C programming, including structures, unions, enumerated data types, pointers, and file handling. It explains the definitions, syntax, and examples of each feature, detailing how to declare and access members, as well as the differences between structures and unions. Additionally, it discusses pointer types, pointer arithmetic, and function pointers.

Uploaded by

Kezial Elizabeth
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

c Programming and Data Structures - Unit II Notes

This document covers advanced features of C programming, including structures, unions, enumerated data types, pointers, and file handling. It explains the definitions, syntax, and examples of each feature, detailing how to declare and access members, as well as the differences between structures and unions. Additionally, it discusses pointer types, pointer arithmetic, and function pointers.

Uploaded by

Kezial Elizabeth
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Unit – II C PROGRAMMING - ADVANCED FEATURES

Structures – Union – Enumerated Data Types – Pointers: Pointers to Variables,


Arrays and Functions – File Handling – Preprocessor Directives.

Structure
Definition:
 Structure is a user-defined data type
 It is used to store the collection of different data types elements.
 Each element of a structure is called a member.
 The struct keyword is used to define the structure.
Structure declaration
Syntax:

struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
Example :
struct student
{
int id;
char name[10];
};
Here, struct is the keyword;
student is the name of the structure;
id and name are the members of the structure

The memory allocation of the structure student is


1000 1002 1003
1011

int id char name[10]

Declaring structure variable


There are two ways to declare structure variable:
1. By struct keyword within main() function
2. By declaring a variable at the time of defining the structure.

1. By struct keyword within main () function


Declare the structure before main() function .
Declare the structure variable inside the main() function.
Syntax:
struct structure-name structure-variable-name
Example:
struct student
{
int id;
char name[50];
};
Then write the following inside the main() function

struct student s1, s2;

2. By declaring a variable at the time of defining the structure.


Syntax:
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
}structure-variable-name;

Example:
struct student
{
int id;
char name[50];
}s1,s2;
Accessing members of the structure

There are two ways to access structure members:

1. By . (dot operator)
2. By -> (structure pointer operator)

1.By . ( dot operator)

The structure members ise accessed with structure variable with dot operator.

Syntax

Structure-variable.structure-member

The code to access the id member of e1 variable by. (member) operator is


s1.id
Example :

#include<stdio.h>
#include <string.h>
struct student
{
int id;
char name[10];
}s1;
int main( )
{
s1.id=101;
s1.name= "Reema”;
printf( "employee 1 id : %d\n", s1.id);
printf( "employee 1 name : %s\n", s1.name);
return 0;
}

2.By -> (structure pointer operator)

The structure members can be accessed with structure pointer variable with ->operator.

Syntax

Structure-variable->structure-member.
Nested Structure:
Declaring one structure within another structure is called as Nested structure.
Example:
struct address
{
char city[20];
int pin;
char phone[14];
};
struct student
{
char name[20];
struct address add;
};
The nested structure members are accessed with following statement
struct student s1;
s1.name=”reema”;
s1.add.city=”Madurai”;

Arrays of Structure
 The collection of multiple structures variables.
 Each variable contains information about different entities.
Example:
struct student
{
int id;
char name[50];
};
struct student s1[10];
Structures and Functions
Structures can be passed as function arguments like all other data types.
We can pass the C structures to functions in 3 ways:
1. Passing individual members of a structure to a function
2. Passing an entire structure to a function.
3. Passing a pointer to structure to a function.
The function can return a structure or a structure member or a pointer to a structure
Example: 1. Passing individual members of a structure to a function
#include<stdio.h>
struct student
{
int id;
char name[20];
}
void display(int a,char n[]);
int main()
{
struct student s1;
clrscr();
printf(“Enter Id”);
scanf(“%d”,&s1.id);
printf(“Enter Name”);
scanf(“%s”,s1.name);
display(s1.id,s1.name);
getch();
return 0;
}
void display(int a,char n[])
{
printf(" Id is: %d \n",a);
printf(" Name is: %s \n", n);
}
2. Passing an entire structure to a function.
#include<stdio.h>
struct student
{
int id;
char name[20];
}
void display(struct student stud );
int main()
{
struct student s1;
clrscr();
printf(“Enter Id”);
scanf(“%d”,&s1.id);
printf(“Enter Name”);
scanf(“%s”,s1.name);
display(s1);
getch();
return 0;
}
void display(struct student stud )
{
printf(" Id is: %d \n",stud. id);
printf(" Name is: %s \n",stud. name);
}
Self Referential Structure
 The self-referential structure is a structure that points to the same type of
structure.
 It contains one or more pointers that point to the same structure.
 Self-referential structure is used in the linked list, trees, graphs and other data
structures.
Example:
struct node
{
int d1 ;
int d2 ;
struct node * link ;
};

typedef in C

 typedef is used to assign alternative names to existing datatypes.


Syntax
typedef <existing_name> <alias_name>
existing name is a data type ,
alias name is a new name for the existing data type.
Example:
typedef unsigned int newtype;
newtype is the new name of the data type unsigned int.
This newtype is used to declare new variables of type unsigned int.
newtype a,b;
This is equivalent to
unsigned int a,b;
Typedef is used in structure.
struct student
{
int id;
char name[20];
};
typedef struct student stud;
stud s1, s2;
Explanation
Create a structure student.
Then declare the structure variable stud of type student with typedef.
The structure variables s1 and s2 are declared with stud.

Union
Definition
 union is a user defined data type.
 It is a collection of different variables of different data types
 In union, all members share the same memory location.
 Size of a union is the size of largest member in union.
 The union keyword is used to define the structure.
Declaring a Union
The union keyword is used to define the structure.
Syntax:

union structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
Example :
union student
{
int id;
char name[10];
};
Here union is the keyword.
student is the name of the union.
id and name are the members of the union.

The memory allocation of the union student is

1000 1002 1003 1010

Int i
Char name[10]
Accessing a Member of a Union

There are two ways to access union members:

1. By . (dot operator)
2. By -> (union pointer operator)

1.By . ( dot operator)

The union members can be accessed with union variable with dot operator.

Syntax

union-variable.union-member

The code to access the id member of e1 variable by. (member) operator is


s1.id
Example :

#include<stdio.h>
#include <string.h>
union student
{
int id;
char name[10];
}s1;
int main( )
{
s1.id=101;
s1.name= "Reema”;
printf( "employee 1 id : %d\n", s1.id);
printf( "employee 1 name : %s\n", s1.name);
return 0;
}

2.By -> (union pointer operator)

The union members can be accessed with union pointer variable with ->operator.

Syntax

union-variable->union-member
Initializing Unions
The union members are initialized using the syntax
Union-variable.union-member=value;
Example

union student
{
int id;
char name[10];
}s1;
int main( )
{
s1.id=101;
s1.name= "Reema”;
printf(“%d”,s1.id);
printf(“%s”,s1.name);
return 0;
}
Arrays of Union Variables
It is the collection of multiple union variables.
Each variable contains information about different entities.
Example:
union student
{
int id;
char name[50];
};
Union student s1[10];
Here s1[10] is the array of union.
Unions Inside Structures
A union can be nested inside a structure and it is called union of structures
union ex
{
int a;
float b;
};
struct mx
{
union ex s;
};

Structures Inside Unions


 A structure can be nested inside a union and it is called union of structures.

struct ex
{
int a;
float b;
};
union mx
{
struct ex s;
};
Difference between Structure and union
Structure Union
The struct keyword is used to define a The union keyword is used to define a
structure. union.
Every member is assigned a unique memory All the data members share a same
location. memory location.
Change in the value of one data member Change in the value of one data
does not affect other data members in the member affects the value of other data
structure. members.
Initialize multiple members at a time. Initialize only the first member at once.
A structure’s total size is the sum of the size A union’s total size is the size of the
of every data member. largest data member.
Users can access or retrieve any member at Users can access only one member at a
a time. time.
Enumerated Data Type
 Enumeration (or enum) is a user defined data type in C.
 It is used to assign names to integral constants.
 The keyword ‘enum’ is used to declare new enumeration types.
Syntax :
enum flag{constant1, constant2, constant3, ....... };
The default value of constant1 is 1 , constant2 is 2 and so on.
Example:
enum week{Mon, Tue, Wed};
enum week day;
day=mon;
The value of day is position of Mon in enum week . So the value of day is 0.

Assigning Values to Enumerated Variables


The enum constants can be assigned with values.
Syntax:
enum flag{constant1=value, constant2=value, constant3=value, ....... };
Example :
enum week{Mon=0, Tue=1, Wed=2};
Properties:

 If there is no value to the enum names, then the compiler will assign the default
values starting from 0.
 The enum names available can have the same value.
o enum week{Mon=0, Tue=1, Wed=1};
 The values to the enum name in any order.
 The unassigned names will get the default value as the previous one plus one.

 The values assigned to the enum names must be integral constant, i.e., it should
not be of other types such string, float, etc.

Example:

#include <stdio.h>
int main()
{
enum weekdays{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday};
enum weekdays w;
w=Monday;
printf("The value of w is %d",w);
return 0;
}
Output :
The value of w is 2

Pointers
 The pointer is a variable used to store the address of another variable.
 This variable can be of type int, char, array, function, or any other pointer.
 The size of the pointer depends on the architecture.
 In 32-bit architecture the size of a pointer is 2 byte.

Declaring a pointer

 The pointer can be declared using * (asterisk symbol).

 It is also known as indirection pointer.

 The format specifier to print the address is %u or %x.

Syntax :

Datatype *pointer-variable;

Example:

Int *p1;

Here p1 is a pointer variable stores the address of integer variable.

Initialize a pointer
After declaring a pointer, initialize the pointer with a variable address.

Syntax

pointer-variable=@variable;
Operators in pointer

 There are two operators in pointers & and *

 The operator & is a “address of” operator.

 The operator * is the “value at address “ operator.

Example:

int a,*p1;

a=10;

p1=&a;

printf(“the address of a is %u”,p1);

printf(“the value of a is %d”,*p1);

a fff4 p1 fa21
10 fff4

Pointer arithmetic:

There are only a few operations are allowed to perform on pointers.

The operations are:


1. Increment/Decrement of a Pointer
2. Addition of integer to a pointer
3. Subtraction of integer to a pointer
4. Subtracting two pointers of the same type
5. Comparison of pointers of the same type.

Increment/Decrement of a Pointer
The pointer can be incremented or decremented with 1..
Syntax:
new_address= current_address + size_of(data type)
new_address= current_address - size_of(data type)
Example
int a,*p1;
p1=&a;

The current value for p1 is 1002


The value for p1++ is 1002+sizeof(int)
1002+2 =1004

Addition and subtraction of integer to a pointer


 To add a value with a pointer, the value is first multiplied by the size of data
type and then added to the pointer.
 To subtract a value with a pointer, the value is first multiplied by the size of
data type and then subtracted from the pointer.

Syntax
new_address= current_address + i * size_of(data type)
new_address= current_address - i * size_of(data type)

here ‘i’ is the value to be added.

Example:
ptr=1002
ptr=ptr+2 will be calculated as
1002+2*sizeof(int)
1002+2*2
1002+4
1006

Subtracting two pointers of the same type


Calculating the difference between the addresses of the two pointers.

Example
int *ptr1,*ptr2;
ptr1=1000
ptr2=1016

 The difference between the two addresses is 16 bytes.


 The size of the int data type is 2 bytes .
 so divide the 16 by 2(16/2)=8 bytes.

Comparison of pointers of the same type


Compare the two pointers by using the comparison operators <,>,<=,>=,!= and ==
Example
*p1<*p2

Illegal arithmetic with pointers

There are various operations which cannot be performed on pointers.

o Address + Address = illegal


o Address * Address = illegal
o Address % Address = illegal
o Address / Address = illegal
o Address & Address = illegal
o Address ^ Address = illegal
o Address | Address = illegal

Types of pointer

1. Null pointer 2.Void pointer 3.Wild pointer 4.Dangling pointer

Null pointer
 pointer created by assigning a null value to the pointer.
 A Null Pointer is a pointer that does not point to any memory location.
 It stores the base address of the segment.

int *p=NULL;

Generic or void pointer


 A void pointer is created by using the keyword void.
 It can be used to store an address of any variable.
 A void pointer can be typecasted to any type.

Example :
void *p1;
int a;
p1=@a;
*(int *)p1;
Wild pointer - If a pointer isn't initialized to anything, it's called a wild pointer.
Dangling Pointer - A dangling pointer is a pointer that refers to a memory location
that has been released or deleted.

Pointer to pointer
 Pointer stores the address of another pointer is known as pointer to pointer.
 The first pointer is used to store the address of a variable .
 The second pointer is used to store the address of the first pointer.

The pointer to pointer is declared as


datatype **pointer-variable
Exampe:
int a,*p1,**p2;
p1=@a;
p2=&p1;
Here the pointer p2 stores the address of another pointer p1;

Arrays of pointer
Arrays of pointer is used to store the address of multiple values of same data type.
Example
int a[10],*p[10];
p[0]=&a[0];
p[1]=&a[1];
p{2}=&a[2];

Function pointer
 Function pointer points to code, not data.
 we do not allocate de-allocate memory using function pointers.
void fun(int a)
{
printf("Value of a is %d\n", a);
}

int main()
{
void (*fun_ptr)(int) = &fun;
(*fun_ptr)(10);
return 0;
}

Passing Arguments to Function Using Pointers

 Passing address to the function.

 The changes made in function are permanent.

Example: Swapping two numbers

#include<stdio.h>

#include<conio.h>

void swap(iint *a,int *b);

int main()

int c=10,d=20;

swap(&c,&d);

getch();

return 0;

void swap(int *a,int *b)

int t;

t=*a;
*a=*b;

*b=t;

Passing Array to Function

The array can be passed to a function like single values.

Syntax to pass an array to the function.

function-name(arrayname);
Example :
display(a)
Syntax to declare the function that receives an array:
1. return_type function(type arrayname[])
2.return_type function(type arrayname[SIZE])
3.return_type function(type *arrayname)

Example
Void display(int a[10]);
void display(int a[]);
void display(*a);

Dynamic Memory Allocation:


The dynamic memory allocation is used to allocate memory at runtime.
The functions used for runtime allocation are:
1. malloc()
2. calloc()
3. realloc()
4. free()

1.malloc() function

 The malloc() function allocates single block of memory.


 It doesn't initialize memory at execution time,.
 It returns NULL if memory is not sufficient.

The syntax of malloc() function is:

ptr=(cast-type*)malloc(byte-size)
Example:
ptr=(int*)mallco(sizeof(int));

2.calloc() function

 The calloc() function allocates multiple block of memory.


 It initially initialize all bytes to zero.
 It returns NULL if memory is not sufficient.

The syntax of calloc() function is:

ptr=(cast-type*)calloc(number, byte-size)
Example:
ptr=(int*)callco(sizeof(int));

3.realloc() function

1. realloc() function is used to change the memory size.

Syntax:
ptr=realloc(ptr, new-size)

4.free() function

 The memory occupied by malloc() or calloc() functions are released by free()


function.
 Otherwise, it will consume memory until program exit.

Syntax;

free(ptr)
Example:
free(ptr1);

File Handling
 File is a collection of similar records of an entity.
 Record is a collection of fields.
Types of file
1. Text files
2. Binary files
1. Text files
Text files are the normal .txt files.
The text files are created using text editors such as Notepad.

2. Binary files

Binary files are stored with .bin files in the computer.


The data is stored in a binary form(0’s and 1’s)
File Operations:

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 Closing a file

Functions for file handling

o There are many functions in the C library to open, read, write, search and close
the file.

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

Creation of a file

Declare a pointer of type file before using a file


FILE *file-pointer;

Opening File: fopen()

The fopen() function is used to open a file.

The syntax of the fopen() is

file-pointer = fopen(“filename”,”file-mode”);

filename is the name of the file to be opened and mode specifies the purpose of
opening the file.

File Modes are

Reading from a file


The file read operations are performed using functions fscanf , fgets, fgetc() and
fgetw()
Syntax:
1.fscanf(file-pointer,”format specifier”,&variables);

2.fgets(char *str, int n, FILE *stream)


 str – Storing the string in this variable
 n - It is the maximum length of the string
 stream – file pointer

3.fgetc(file-pointer);

4.fgetw(file-pointer);

Writing in to a file

The file write operations can be performed by the functions fprintf , fputs and fputc()
Syntax:
1.fprintf(filepointer,”format specifier,variables);
2.fputs(“string”,file-pointer);
3.fputc(‘single character’,file-pointer);
Reading and writing to a binary file
Functions fread() and fwrite() are used for reading from and writing to a file on the
disk respectively in case of binary files.
Closing a file
The file should be closed after reading/writing.
Closing a file is with the fclose() function.
Syntax:
fclose(fptr);
fseek() function

The fseek() function is used to set the file pointer to the specified offset.

It is used to write data into file at desired location.

Syntax:

fseek(file-pointer, offset, position)


 offset − This is the number of bytes to offset from position.
 position − This is the position added with the offset .

Three possible values of position are


SEEK_SET - Beginning of file
SEEK_CUR -Current position of the file pointer
SEEK_END -End of file
Ftell() function :
The ftell() function returns the current file position of the specified file.
Syntax :
ftell(filepointer)

rewind() function
The rewind() function sets the file pointer at the beginning of the file.
Syntax:
rewind(file-pointer)
Example program:
#include<stdio.h>
#include<conio.h>
int main()
{
file *fp1,fp2;
int n,a[10],b,i;
fp1=fopen(“file1.txt”,”w”);
printf(“enter number of elements”);
scanf(“%d”,&n);
printf(“enter the array elements”);
for(i=1;i<=n;i++)
{
scanf(“%d”,&a[i]);
fprintf(fp1,”\n%d”,a[i]);
}
fclose(fp1);
fp2=fopen(“file1.txt”,”r”);
printf(“the content of the file is \n”);
while(!feof(fp1))
{
fscanf(fp2,”%d”,b);
printf(“%d”,b);
}
fclose(fp2);
getch();
return 0;
}

Strings
 String is an array of characters.
 NULL character (\0) will automatically be inserted at the end of the string.

String Declaration

Strings are declared as a character array.

Syntax:
char stringname[size];
Example
char name[10];
Reading and writing a string
gets() – This function is used to read a string
puts – This function is used to display the string
%s – format specifier is used to read a string with scanf() function
Example :
char name[10];
scanf(“%s”,name);
gets(name);
puts(name);

String functions:
No Function Description
.
1) strlen(string_name) returns the length of string name.
2) strcpy(destination, copies the contents of source string to
source) destination string.
3) strcat(first_string, joins first string with second string. The
second_string) result of the string is stored in first string.
4) strcmp(first_string, compares the first string with second string.
second_string) If both strings are same, it returns 0.
5) strrev(string) returns reverse string.
6) strlwr(string) returns string characters in lowercase.
7) strupr(string) returns string characters in uppercase.
Example
char firstname[]=”reema”
char lastname[]=”thareja”
1.strlen(firstname)- output is 5
2.strcpy(name,”data structures”)- the value of name is data structures
3.strcat(firstname,lastname)- now the value of fistname is reema thareja
4.strcmp(firstname,lastname)- the output is not zero because the two string are
different.
5.strrev(lastname)- the output is ajerath
6.strupr(lastname) – the output is THAREJA.

Preprocessor directives
The C preprocessor is a micro processor used by compiler to transform the c program
before compilation.

All preprocessor directives starts with hash # symbol.

Preprocessor directives.

There are 4 Main Types of Preprocessor Directives:


1. Macros
2. File Inclusion
3. Conditional Compilation
4. Other directives

1. Macros

Macros are pieces of code in a program with specific name.


The compiler replaces the name with the actual piece of code during compilation.
The ‘#define’ directive is used to define a macro.

There are two types of macros:

1. Object Macros
2. Function Macros

Object macro:

Used to define the symbolic constants.

Example:

#define pi 3014

Function Macros

Used to define a function

Example :

#define area(I,b)(l*b)

2. File Inclusion

This type of preprocessor directive used to include a file in the source code program.

There are two types of files

1.Standard files

These files contain definitions of pre-defined functions like printf(), scanf(), etc.

Syntax:
#include< file_name >
Example:
#include<stdio.h>

2.User defined files

The user defined files are included with the syntax #include “filename”

Example:

#include “program1.c”

3.Conditional Compilation
These directives are used to compile a specific portion of the program or to skip the
compilation of some specific part of the program based on some conditions.
This can be done with the help of the two preprocessing commands ‘ifdef‘ and
‘endif‘.

Syntax:
#ifdef macro_name
statement1;
statement2;
statement3;
.
.
.
statementN;
#endif

4. Other Directives

 undef Directive: The #undef directive is used to undefine an existing macro.

 #pragma Directive: This directive is used to turn on or off some features.

 #pragma startup and #pragma exit: Used to run a function before program
startup and. before program exit

 #pragma warn Directive: This directive is used to hide the warning


message.

o #pragma warn -rvl: This directive hides those warnings raised when a
function does not return a value.
o #pragma warn -par: This directive hides warnings raised when a
function does not use the parameters passed to it.

Preprocessor Operators

The Macro Continuation (\) Operator


A macro is written in a single line.
The macro continuation operator (\) is used to continue a macro for more than
one line.
.Example:
#define area(a,b) \
printf(a*b)
The Stringize (#) Operator
Used Receives the parameter from the main functions.
Converts a macro parameter into a string constant
Token Passing Operator(##)
Combines two arguments.

You might also like