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

Unit 5 Adv C

The document discusses typedef in C programming and how it provides meaningful names to existing variables. It also discusses command line arguments in C and how to handle them using argc and argv. The document further explains variable arguments in C functions using stdarg.h and va_list.

Uploaded by

Hardik Rathore
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)
35 views

Unit 5 Adv C

The document discusses typedef in C programming and how it provides meaningful names to existing variables. It also discusses command line arguments in C and how to handle them using argc and argv. The document further explains variable arguments in C functions using stdarg.h and va_list.

Uploaded by

Hardik Rathore
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/ 24

Unit-V

Advanced topic

typedef in C

The typedef is a keyword used in C programming to provide some meaningful names to the already
existing variable in the C program. It behaves similarly as we define the alias for the commands. In
short, we can say that this keyword is used to redefine the name of an already existing variable.

Syntax of typedef

1. typedef <existing_name> <alias_name>

In the above syntax, 'existing_name' is the name of an already existing variable while 'alias name' is
another name given to the existing variable.

For example, suppose we want to create a variable of type unsigned int, then it becomes a tedious task
if we want to declare multiple variables of this type. To overcome the problem, we use a
typedef keyword.

1. typedef unsigned int unit;

In the above statements, we have declared the unit variable of type unsigned int by using a
typedef keyword.

Now, we can create the variables of type unsigned int by writing the following statement:

1. unit a, b;

instead of writing:

1. unsigned int a, b;

Till now, we have observed that the typedef keyword provides a nice shortcut by providing an
alternative name for an already existing variable. This keyword is useful when we are dealing with the
long data type especially, structure declarations.

1. #include <stdio.h>
2. int main()
3. {
4. typedef unsigned int unit;
5. unit i,j;
6. i=10;
7. j=20;
8. printf("Value of i is :%d",i);
9. printf("\nValue of j is :%d",j);
10. return 0;
11. }

Output

Value of i is :10
Value of j is :20
Command Line Arguments in C

The arguments passed from command line are called command line arguments. These arguments are
handled by main() function.

To support command line argument, you need to change the structure of main() function as given
below.

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

Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name always.

Example

Let's see the example of command line arguments where we are passing one argument with file name.

1. #include <stdio.h>
2. void main(int argc, char *argv[] ) {
3.
4. printf("Program name is: %s\n", argv[0]);
5.
6. if(argc < 2){
7. printf("No argument passed through command line.\n");
8. }
9. else{
10. printf("First argument is: %s\n", argv[1]);
11. }
12. }

Run this program as follows in Linux:


1. ./program hello

Run this program as follows in Windows from command line:

1. program.exe hello

Output:

Program name is: program


First argument is: hello

If you pass many arguments, it will print only one.

1. ./program hello c how r u

Output:

Program name is: program


First argument is: hello

But if you pass many arguments within double quote, all arguments will be treated as a single argument
only.

1. ./program "hello c how r u"

Output:

Program name is: program


First argument is: hello c how r u

You can write your program to print all the arguments. In this program, we are printing only argv[1],
that is why it is printing only one argument.

when you want to have a function, which can take variable number of arguments, i.e., parameters,
instead of predefined number of parameters. The C programming language provides a solution for this
situation and you are allowed to define a function which can accept variable number of parameters
based on your requirement. The following example shows the definition of such a function.

int func(int,...){
.
.
.
}
int main(){
func(1,2,3);
func(1,2,3,4);
}
It should be noted that the function func() has its last argument as ellipses, i.e. three dotes (...) and the
one just before the ellipses is always an int which will represent the total number variable arguments
passed. To use such functionality, you need to make use of stdarg.h header file which provides the
functions and macros to implement the functionality of variable arguments and follow the given steps −
● Define a function with its last parameter as ellipses and the one just before the ellipses is always
an int which will represent the number of arguments.
● Create a va_list type variable in the function definition. This type is defined in stdarg.h header
file.
● Use int parameter and va_start macro to initialize the va_list variable to an argument list. The
macro va_start is defined in stdarg.h header file.
● Use va_arg macro and va_list variable to access each item in argument list.
● Use a macro va_end to clean up the memory assigned to va_list variable.
Now let us follow the above steps and write down a simple function which can take the variable number
of parameters and return their average −
Live Demo
#include<stdio.h>
#include<stdarg.h>

double average(int num,...){

va_list valist;
double sum =0.0;
int i;

/* initialize valist for num number of arguments */


va_start(valist, num);

/* access all the arguments assigned to valist */


for(i =0; i < num; i++){
sum += va_arg(valist,int);
}

/* clean memory reserved for valist */


va_end(valist);

return sum/num;
}

int main(){
printf("Average of 2, 3, 4, 5 = %f\n", average(4,2,3,4,5));
printf("Average of 5, 10, 15 = %f\n", average(3,5,10,15));
}
When the above code is compiled and executed, it produces the following result. It should be noted that
the function average() has been called twice and each time the first argument represents the total
number of variable arguments being passed. Only ellipses will be used to pass variable number of
arguments.
Average of 2, 3, 4, 5 = 3.500000
Average of 5, 10, 15 = 10.000000
referential structure

self-referential structure is a structure that points to the same type of structure. It


ains one or more pointers that ultimately point to the same structure.

Structures are a user-defined data structure type in C and C++.


The main benefit of creating structure is that it can hold the different predefined data
s.
It is initialized with the struct keyword and the structure's name followed by this struct
ord.
We can easily take the different data types like integer value, float, char, and others
n the same structure.
It reduces the complexity of the program.
Using a single structure can hold the values and data set in a single place.
In the C++ programming language, placing struct keywords is optional or not mandatory,
t is mandatory in the C programming language.
Self-referential structure plays a very important role in creating other data structures
Linked list.
In this type of structure, the object of the same structure points to the same data
ture and refers to the data types of the same structure.
It can have one or more pointers pointing to the same type of structure as their member.
The self-referential structure is widely used in dynamic data structures such as trees,
d lists, etc.
do we require a Self-referential structure?

referential structure plays a vital role in the linked list, trees, graphs, and many more data
tures. By using the structure, we can easily implement these data structures efficiently.
defining a particular node, the structure plays a very important role. In a linked list, the
ture is used to store the data information and the address of the next node in the given
d list. Mainly the data part is of integer type, and the link address part is of pointer type,
h holds the address of the next node, so that it can for the Link ultimately.

e all know, the role of a linked list is used to store the data elements of the same type, in
h address locations are not at the consecutive difference. In this linear linked list, the
ent node holds the address of the next node so that it ultimately forms the Link between
urrent node and the next node.

ures of Java - Javatpoint


in the linked list, we will define a common structure, which contains the data and address
er to carry the address of the next node, so to form the multiple nodes, we from each node
g the node structure.

ke a static data structure such as an array where the size of the array limits the number of
ents that can easily to inserted into the array, a self-referential structure can dynamically
panded or contracted.

ations like the insertion or deletion of nodes in a self-referential structure involve


ghtforward alteration of pointers.

ed list
A linked list is a useful data storage method, and it is very easy to implement it in C
ramming Language.
Several kinds of linked lists, including single linked lists, double linked lists, and binary
.
Each type is suited for certain types of data storage.
The one thing that these lists have in common is that the links between data items are
ed by the information contained in the items themselves, in the form of pointers.
The linked list is distinctly different from arrays, in which the links between data items
t from the layout and storage of the array.

we will discuss the self-referential structure in more detail using the linked list concepts.

understand the concept of self-referential structure in more detail using the example
ioned below:

mple 1: Creating a random self-referential structure in the C programming language.

// Dummy Self-referential structure in C language


struct node // Creating a node of structure type contains data
// part of integer type and a pointer of structure type to
// hold the address of the next node
{
int d1 ; // data 1 of integer type
int d2 ; // data 2 of integer type
struct node * link ; // Self referential structure link is pointing the same
// structure of the type node
};
Int main()
{
Struct node obj; // Creating an object of the node type, this objec
/ consists of three parts one is data 1 and
// second is of data 2, and third is of link type pointer
// carries the address of the next node.
Return 0 ;
}

mple 2: Creating a random self-referential structure in a python programming language.

# Dummy Self-referential structure in python language


class node: # Creating a node that contains data
# part of and a pointer of node type to
# hold the address of the next node
def __init__(self):
self.data1=0
self.data2=' '
self.link=None # Self-referential structure link is pointing the same
# structure of the type node

if __name__ == '__main__':
ob=node()
# Creating a object of node type, this object is
# consists of three parts one is data 1 and
# second is of data 2 and third is of link type pointer
# carries the address of the next node

s of self-referential structure
Single Link self-referential structure
Multiple Link self-referential structures

e Link self-referential structure

he name suggests, we can easily predict that these structures consist of a single Link,
ly the only one pointer link of structure type pointing to the same structure. To better
rstand it, we can connect this concept with the singly linked list.

singly linked list, there is only a single pointer that carries the address of the next node,
hat pointer variable is of the structure node type itself. It is mainly used when we want to
the different data items by fetching out them from various addresses and connecting all
em by storing the address of one data item into the linked part of the other node. In this
we can easily connect all the data items by using these connecting links.

look at the working of single link self-referential structure with the help of an example:

// Single link self-referential structure implementation in C language


#include<stdio.h>
#include<stdlib.h>
struct node
{
int info ;
struct node *link ; // Self-referential structure link is pointing the same
// structure of the type node
};

struct node *START = NULL ; // start pointer to control the linked list //
struct node* createnode() ;
void insertatlast() ; // insert node at last //
void deleteatfirst() ; // delete node at first //
void viewlist() ;
void insertatfirst() ;
int getlength() ;
int menu() ;
void insertafteranynode() ;
void deleteatlast() ;
void deleteatposition() ;

struct node* createnode() // create node dynamically //


{
struct node *n ;
n = malloc( sizeof(struct node) ) ;
return ( n ) ;
}
void insertatlast()
{
struct node *temp ,*t ;
temp = createnode() ;
printf( "Enter the data in node \n " ) ;
scanf( " %d" , &temp->info ) ;
temp->link = NULL ;
if ( START == NULL )
START = temp ;
else
{
t = START ;
while ( t->link != NULL )
{
t = t->link ;
}
t->link = temp ;
}
}
void deleteatfirst() // delete node at first //
{
if ( START == NULL )
printf ( "List is empty \n " ) ;
else
{
struct node *q ;
q = START ;
START = START->link ;
free( q ) ;
}
}
void viewlist()
{ struct node* t ;
if ( START == NULL )
{
printf ( "No List \n " ) ;
}
else
{
t = START ;
while ( t != NULL )
{
printf ( " %d" , t->info ) ;
t = t->link ;
}
}
}
void insertatfirst()
{ struct node*New ;
New = createnode() ;
printf ( "Enter the data in node \n " ) ;
scanf ( " %d" , &New->info ) ;

if ( START == NULL )
START = New ;
else
{
New->link = START ;
START = New ;
}
}
int getlength()
{
int count = 0 ;
struct node* t ;
if ( START == NULL )
printf ( "List is empty \n " ) ;
else
{
t =START ;
while ( t != NULL )
{
count = count + 1 ;
t = t->link ;
}
}
return count ;
}
void insertafteranynode()
{
int position ;
struct node* newnode ,*t ;
if ( START == NULL )
printf ( "List is empty \n " ) ;
else
{
printf ( "Enter position after which you want to add: \n " ) ;
scanf ( " %d" , &position ) ;
if ( position > getlength() )
{
printf ( "Wrong position \n " ) ;
insertafteranynode() ; // recursion //

}
else
{
int i = 1 ;
newnode = createnode() ;
printf ( "Enter Data \n " ) ;
scanf ( " %d" , &newnode->info ) ;
newnode->link = NULL ;
if ( START == NULL )
START = newnode ;
else
{
t = START ;
while ( i < position )
{
t = t->link ;
i++ ;
}
newnode->link = t->link ;
t->link = newnode ;
}
}
}
}
void deleteatlast()
{
struct node* t , *q ;
if ( START == NULL )
{
printf ( "List is empty \n " ) ;
}
else
{
t = START ;
q = START ;
while ( t->link != NULL )
{
q=t;
t = t->link ;
}
if ( t == START )
{
START == NULL ;
}
else
{
q->link = NULL ;
free( t ) ;
}
}
}
void deleteatposition()
{
struct node *t , *q ;
int position , i = 1 ;
t = START ;
if ( START == NULL)
{
printf ( "List is empty \n " ) ;
}
else
{
printf ( "Enter position after which you want to delete: \n " ) ;
scanf ( " %d" , &position ) ;
if ( position > getlength() )
{
printf ( "Wrong position \n " ) ;
deleteatposition() ; // recursion //

}
else
{
while ( i < position )
{
q=t;
t = t->link ;
i++ ;
}
if ( t == START )
{
START == NULL ;
}
else
{
q->link = t->link ;
free( t ) ;
}
}
}
}
int menu()
{
int ch ;
printf ( " \t \t \t 1.ADD NODE LAST IN LINK \n " ) ;
printf ( " \t \t \t 2.ADD NODE AT FIRST IN LINK \n " ) ;
printf ( " \t \t \t 3.VIEW LIST IN LINK \n " ) ;
printf ( " \t \t \t 4.DELETE NODE AT FIRST IN LINK \n " ) ;
printf( " \t \t \t 5. TO SEE THE LENGTH OF LIST \n " ) ;
printf ( " \t \t \t 6. INSERT NODE IN BETWEEN \n " ) ;
printf ( " \t \t \t 7.DELETE NODE AT LAST IN LINK \n " ) ;
printf ( " \t \t \t 8.DELETE NODE AT SPECIFIC POSITION IN LINK \n " ) ;
printf ( " \t \t \t 9.EXIT \n " ) ;
printf ( "ENTER THE CHOICE \n " ) ;
scanf ( " %d" , &ch ) ;
return( ch ) ;
}
void main()
{ int k ;
while ( 1 )
{
switch ( menu() )
{
case 1 :
insertatlast() ;
break ;
case 2 :
insertatfirst() ;
break ;
case 3 :
viewlist() ;
break ;
case 4 :
deleteatfirst() ;
break ;
case 5 :
k = getlength() ;
printf ( "THE LENGTH OF THE LIST IS %d \n " , k ) ;
break ;
case 6 :
insertafteranynode() ;
break ;
case 7 :
deleteatlast() ;
break ;
case 8 :
deleteatposition() ;
break ;
case 9 :
exit( 0 ) ;
break ;
default :
printf ( " Not available \n " ) ;
}
}
}

utput of the above program is:


# Single link self-referential structure implementation in Python language
class node:
def __init__(self):
self.d1=0
self.d2=0
self.link=None

if __name__ == '__main__':
obj1=node() # Node1

# Initialization
obj1.link = None
obj1.d1 = 17
obj1.d2 = 14
obj2=node() # Node2

# Initialization
obj2.link = None
obj2.d1 = 36
obj2.d2 = 24

# Linking obj1 and obj2


obj1.link = obj2

# Accessing data members of obj2 using obj1


print(obj1.link.d1)
print(obj1.link.d2)

utput of the above program is:

iple Link self-referential structures

e name suggests, we can easily predict that these types of the structure consist of multiple
here we will make use of two pointer links of structure type which is pointing to the same
ture, to understand it better, we can connect this concept with a doubly-linked list.

doubly-linked list, two single pointers carry the address of the next node and the previous
, and that pointer variable is of the structure node type itself. It is mainly used when we
to store the different data items by fetching out them from various addresses and
ecting all of them by storing the address of one data item into the linked part of the other
; in this way, we can easily connect all the data items by using these connecting links.

us look at the working of, multiple link self-referential structure with the help of an
ple:

// Multiple link self-referential structure implementation in C language


#include<stdio.h>
#include<stdlib.h>
struct node
{
int info ;
struct node *prev ; // Self-referential structure link is pointing the same
// structure of the type node but to the previous node

struct node *next; // Self-referential structure link is pointing the same


// structure of the type node but to the next node

};

struct node * START = NULL ; // Start pointer of the list and initially it must be nul
represents that no node is present
void insertnodeatfirst() ;
void deleteatfirst() ;
void viewlist() ;
int menu() ;
void insertnodeatfirst() // Inserting the node at first
{
struct node * newnode ;
newnode = malloc( sizeof( struct node ) ) ;
printf ( "Enter Data: \n " ) ;
scanf ( " %d" , &newnode->info ) ;
newnode->prev = NULL ;
newnode->next = NULL ;
if ( START == NULL )
START = newnode ;
else
{
START->prev = newnode ;
newnode->next = START ;
START = newnode ;
}
}
void deleteatfirst() // deleting the first node
{
struct node * temp ;
if ( START == NULL )
printf ( "List is empty \n " ) ;
else
{
temp = START ;
START = START->next ;
START->prev = NULL ;
free( temp ) ;
}
}
void viewlist() // displaying all the nodes in the list
{
struct node * t ;
if ( START == NULL )
printf ( "List is empty \n " ) ;
else
{
t = START ;
while ( t != NULL )
{
printf ( " %d \n " , t->info ) ;
t = t->next ;
}
}
}
int menu()
{ int n ;
printf ( " \t \t \t 1. VIEW LIST \n " ) ;
printf ( " \t \t \t 2. INSERT AT FIRST IN LIST \n " ) ;
printf ( " \t \t \t 3. DELETE AT FIRST IN LIST \n " ) ;
printf ( " \t \t \t 4. EXIT \n " ) ;
printf ( "ENTER YOUR CHOICE \n " ) ;
scanf ( " %d" , &n ) ;
return ( n ) ;
}
int main()
{
while ( 1 )
{
switch ( menu() )
{
case 1 :
viewlist() ;
break ;
case 2 :
insertnodeatfirst() ;
break ;
case 3 :
deleteatfirst() ;
break ;
case 4 :
exit ( 1 ) ;
break ;
default :
printf ( " NOT AVAILABLE \n " ) ;
}
}
}

utput of the above program is:


# Multiple link self-referential structure implementation in Python language
class node:
def __init__(self):
self.data = 0
self.prev = None
self.next = None

if __name__ == '__main__':
obj1=node() # Node1

# Initialization
obj1.prev = None
obj1.next = None
obj1.data = 15

obj2=node() # Node2

# Initialization
obj2.prev = None
obj2.next = None
obj2.data = 20

obj3 = node() # Node3

# Initialization
obj3.prev = None
obj3.next = None
obj3.data = 25

# Forward links
obj1.next = obj2
obj2.next = obj3

# Backward links
obj2.prev = obj1
obj3.prev = obj2

# Accessing data of obj1, obj2 and obj3 by obj1


print(obj1.data , end='\t')
print(obj1.next.data , end='\t')
print(obj1.next.next.data)

# Accessing data of obj1, obj2 and obj3 by obj2


print(obj2.prev.data , end='\t')
print(obj2.data , end='\t')
print(obj2.next.data)
# Accessing data of obj1, obj2 and obj3 by obj3
print(obj3.prev.prev.data , end='\t')
print(obj3.prev.data , end='\t')
print(obj3.data)

utput of the above program is:

20 25
20 25
20 25

You might also like