PSPC Unit-5
PSPC Unit-5
Syntax:
data_type * variable_name.
Example:
int *a; or int* a;
In above declaration * placed in two different places ,the first one the * prefix with
variable and second one * followed by datatype both are right you will follow any one
these.
int i=24;
int *ptr; // declaration of pointer
ptr = &i; // assigning address into ptr
Value 24 11224
In above fig, i is a variable it holds the value 24 and address of I is 11224(let assume).
Pointer always stores the address of variable so, ptr is a pointer , it stores the address of I (&i) i.e
11224.
Pointer variable also stored at different location i.e 11001.
i 24 11224
Types of Pointers:
Here one type of pointer cannot points another type of data that means integer pointer
can points only integer data only (integer pointer stores the int variable address only).
Character pointer points character data only, same as float and double.
Un-typed pointer is nothing but generic pointers (void pointer). void pointer can point
any type of data.
Size of pointers:
The pointer occupy the same amount of memory for the all the data types, but how
much space they occupy will depends on the compiler where the code is going to
run.(like integer , integer size also differ from compiler to compiler.).
.If we use 16bit compiler it occupy 2 bytes of memory for all data types , if we use 32
bit compiler the pointer occupies 4 bytes of memory .
We will see the following table because the integer and pointer sizes are same based on
compilers.
Example :
Write a program to find the size of pointers with different data types
#include<stdio.h>
int main()
char *cptr;
int *iptr;
float *fptr;
double *dptr;
return 0;
Here ptr is a pointer variable it stores the address of the variable, if we are not assign any
address to the pointer variable it stores the garbage value.
In this stores the address of the a is stored in ptr. When we will print the ptr then prints
the address of the a.
To access the value inside a particular address, then we will prefix * with pointer name or
address i.e *ptr.
int a=24;
int *ptr; // declaration of pointer
ptr = &a; // assigning address into ptr
variable a ptr
Value 24 11224
Example:
Explanation :
#include<stdio.h>
int main() i ptr
{
int i=100; 100 1241224
int *ptr;
ptr=&i; 1241224
printf("\n%d",i); 6122468
printf("\n%d",&i);
printf("\n%d",ptr);
printf("\n%d",&ptr);
printf("\n%d",*ptr); i=100
printf("\n%d",*(&i)); &i=1241224
return 0; ptr= 1241224
} &ptr=6122468
*ptr=100
*(&i)=100
OUTPUT:
100
1241224
1241224
6122468
100
100
Pointer address operator is denoted by ‘&‘ Indirection operator is denoted by ‘*’ symbol
symbol When we use ampersand symbol as a when we use asterisk symbol as a prefix with
prefix to a variable name, it gives the address variable name, it gives the value which is
of that variable. inside specified address .it is also called as
lets take an example – &n - It gives an address value operator or dereferencing operator.
on variable n Working of address operator
#include<stdio.h> #include<stdio.h>
M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 5
PSTC UNIT-V POINTERS
Value of n is : 10 Value of n is : 10
Value of &n is : 1002 Value of &n is : 10
Formula:
Address + 1 = Address
Address++ = Address
++Address = Address
Pictorial representation :
i ptr ptr
After
20 1224 1226
increment
1224 1508 1508
Explanation :
#include<stdio.h>
int main()
{
int *ptr=(int *)1000;
ptr=ptr+1;
printf("New Value of ptr : %u",ptr);
return 0;
}
Output :
New Value of ptr : 1002
ptr=ptr+1;
printf("New Value of ptr : %u",ptr);
return 0;
} Output :
New Value of ptr : 1008
Note :
In C, the programmer may add or subtract integers from pointers, we can also subtract
one pointer from the other.
An integer value can be added or subtracted from pointer variables but one pointer
variable cannot be added to another pointer variables. That mean only values can be
added.
Example :
int *ptr1=10;
int *ptr2=20;
*ptr1+*ptr2 it is possible i.e values can be added so the value is 30;
ptr+ptr2 Not possible i.e addresses cannot be added.
Example 3:
#include<stdio.h>
int main()
{
int x=10;
int y=25;
int *ptr1=&x;
int *ptr2=&y;
printf("x+y=%d",*ptr1+*ptr2);
return 0;
}
Output:
x+y=35
Example 4:
#include<stdio.h>
int main()
{
int n *p1,*p2;
p1=&n;
p2=p1+2;
printf("the difference between p1 & p2 is %d memory segments”,p2-p1);
return 0;
}
Explanation:
#include<stdio.h>
int main()
int arr[5]={10,20,30,40,50};
int *ptr;
ptr=arr;
printf("%u\n",*++ptr+3); statement1
printf("%u\n",*(ptr--+2)+5); statement2
printf("%u\n",*(ptr+3)-10); statement3
return 0;
OUTPUT:
} 23
45
30
Explanation:
arr[5]={10,20,30,40,50}
10 20 30 40 50
1000
1000
Statement 1:
*++ptr+3 (R to L)
*1002+3
20+3 => 23
Statement 2:
*(ptr - - +2)+5
*(1002 +2)+5
*1006+5
40+5 => 45
Statement 3:
*(ptr+3)-10
*(1000+3)-10
*1006-10
40-10 => 30
Example 1: Example 2:
#include<stdlib.h> #include<stdio.h>
int main() #include<stdlib.h>
{ int main()
int * ptr=NULL; {
printf("the value of ptr is :%x",ptr); int num=24;
if(ptr) int *ptr1=#
printf("\nPointer is not a NULL pointer"); int *ptr2;
if(!ptr) int *ptr3=0;
printf("\nPointer is a NULL pointer"); if(ptr1==0)
return 0; printf("\nPointer 1 : NULL");
else
} printf("\nPointer 1 : NOT NULL");
if(ptr2==0)
printf("\nPointer 2 : NULL");
OUTPUT: else
pointer is a NULL pointer printf("\nPointer 2 : NOT NULL");
if(ptr3==0)
printf("\nPointer 3 : NULL");
else
OUTPUT:
Pointer 1: NOT NULL
Pointer 2: NULL
Pointer 3:NULL
Note:
Example :
#include<stdio.h>
int main()
int x=10;
char ch='R';
return 0;
Note : A compilation error will be generated if we assign a pointer of one type to a pointer of
another type without a cast.
Example:
#include<stdio.h>
void sum(int*,int*,int*);
int main()
int num1,num2,total;
scanf("%d%d",&num1,&num2);
sum(&num1,&num2,&total);
printf("\Total =%d",total);
return 0;
*t=*a+*b;
OUTPUT:
Enter two value num1 & num2:
10
20
Total = 30
1. Call by value
2. Call by reference
Call by Value
In call by value method, the value of the variable is passed to the function as
parameter. The value of the actual parameter cannot be modified by formal parameter. Different
Memory is allocated for both actual and formal parameters. Because, value of actual parameter is
copied to formal parameter.
Example Explanation:
#include<stdio.h>
void swap(int , int ); main (calling function)
int main()
{ 24 7
int a = 24, b = 7;
printf("\nValues before swap \n a = %d and b = %d", a, b); 27 27
2048 2017
swap(a,b);
printf(" \nValues after swap \n a = %d and b = %d", a, b); swap (called function)
return 0;
}
x y
void swap(int x, int y) 24 7 7 24
{
2049 2785
int temp; temp
temp = x;
24
x = y;
y = temp; 7000
}
OUTPUT
Values before swap
a =24 and b = 7
Values after swap
a =24 and b = 7
Call by reference
In call by reference method, the address of the variable is passed to the function as
parameter. The value of the actual parameter can be modified by formal parameter. Same
memory is used for both actual and formal parameters since only address is used by both
parameters.
Example:
#include<stdio.h> main (calling function)
void swap(int *, int *);
int main() 24 7 7 24
{
int a = 22, b = 44; 2048 27
2017
printf("\nValues before swap \n a = %d and b = %d", a, b);
swap(&a,&b); 27
swap (called function)
printf(" \nValues after swap \n a = %d and b = %d", a, b);
x y
return 0;
} 2048 2017
void swap(int *x, int *y)
2049 2785
{ temp
int temp; 24
temp = *x;
*x = *y; 7000
*y = temp;
}
OUTPUT:
Values before swap
a =22 and b = 44
Values after swap
a =44 and b = 22
1 2 3 4 5
100 102 104 106 108
The name of the array is the starting address of array in memory. It is
also known as “Base address “.
int *ptr;
ptr = &arr[0];
Ptr is made to point the first element of the array.
Ex:-
main( )
{
int arr[ ]={1,2,3,4,5};
printf(“Address of array=%p %p %p”,arr,&arr[0],&arr);
ptr =&arr[2];
1 2 3 4 5
100 102 104 106 108
ptr =arr[3];
If pointer variable ptr holds the address of the first element in the array.
Note:-
An error is generated if an attempt is made to change the address of the array.
Example 1:
#include <stdio.h>
int main( )
int a[ ]={1,2,3,4,5,6,7,8,9};
int *p1,p2;
p1=a; OUTPUT:
123456789
p2=&a[8];
while(p1<=p2)
{
printf(“%d\t”,*p1);
p1++;
}
return 0;
}
Example 2:
int main( )
{
int arr[ ]={1,2,3,4,5};
int *ptr,i;
ptr=&arr[2];
*ptr= 24;
*(ptr+1)=0;
*(ptr-1)=1;
printf(“\n array is”);
for(i=0;i<5;i++)
{ OUTPUT:
1 1 24 0 5
printf(“%d\t”,*(arr+1));
}
}
Syntax-1
const <type of pointer> *<pointer name>
Ex:-
const int *ptr;
(OR)
Syntax-2
<type of pointer> const *<pointer name>
Ex:-
int const *ptr;
These pointer can change the address the point to but cannot change the value at the
address they are pointing to.
Ex:-
main( )
{
int a=10;
cons tint *ptr=&a; ptr to const value.
*ptr=30; error because value we can’t change
return 0;
}
a b a 30 b
Example:2
10 20 10 20
main() 30
{ 1024 1026 30
1024 not ok 1026
//Definition of the variable. 30
int a=10; 1024
1024
int b=20;
const int*ptr=&a; 1029 1029
ptr=&b; It works because address is not constant.
return 0;
}
1) const int *ptr=&a;
a b
10 20
1024 1026
1024 1026
1000 1000
3001 3001
a b
10 20
1000 1024
1000
3001
3000
1)int a=24; a p pp
int *p=&a;
int **pp=&p; 24 1000 2000
1000 2000 3000
a is a variable stored at 1000 location. p is pointer which contains the address or a
variable and pp is double pointer which contains the address of p pointer.
**pp Explanation:
It will give value at location 2000 ,which is 1000.
**p will give the value at location 1000 , which is 24.
Value of **pp=24
Value of *p=24
Value of a=24
Value of p=1000
Value of pp=3000
Value of &a=1000
Example :
int main( )
{
int num=7;
int *p,**pp;
p=#
OUTPUT:
pp=&p; Adreess of number variable 644523
Adreess in p variable 644523
printf(“\n%d address of number variable”,&num); Value of *p is 7
printf(“\nAddress in p variable-%d”,p); Adreess in pp is 521342
Value of *pp is 644523
printf(“\nValue of *p is %d”,*p); Value of **pp is 7
printf(“\nAddress of pp is %d”,pp);
printf(“\nValue of *pp is %d”,*pp);
Example 2 :
#include<stdio.h>
int main( )
{ OUTPUT:
int a=24; address of variable a: 1224
int *p,**pp,***ppp,****pppp; value of variable *p : 24
p=&a; adress of pp is: 6453
pp=&p; Address * pp is : 1224
ppp=&pp; Value of **pp is: 24
pppp=&ppp; adress of ppp is 7624
printf("%d\n address of variable a : ",p); Address in * ppp is:6453
printf("\n value of variable a :%d",*p); adresss of**ppp is:1224
printf("adress of pp is: %d",pp); value inside ***ppp is 24
printf("\n Address inside pp is %d",*pp); adress of pppp is: 9234
printf("\n Value of **pp is: %d",**pp); Address * pppp is: 7624
printf("adress of ppp is: %d",ppp); adresss of **pppp is 6453
printf("\n Address inside ppp is %d",*ppp); adress inside ***pppp is: 1224
printf("\n adresss of *ppp is: %d",**ppp); value inside the ****pppp: 24
printf("\n value inside ***ppp is:%d",***ppp);
printf("adress of pppp is: %d",pppp);
printf("\n Address inside pppp is %d",*pppp);
printf("\n adresss of *pppp is: %d",**pppp);
printf("\n adress inside ***ppppis:%d",***pppp)
printf("\n value inside the ****pppp is
:%d",****pppp);
return 0;
}
Explanation :
a p pp ppp pppp
1224 9234
24 6453 7624
1224
6453 7624 9234 3879
when the double quotes are used ,NULL character (‘\0’) is automatically appends to the
end of string.
When a string is declared like this the compiler sets avoid a contiguous block or memory
10 bytes long to hold characters and initiate its first four characters cse\0 .
Example:
#include <stdio.h>
int main
()
{
char str[ ]=”Hello Cse”; OUTPUT:
char *pstr; Hello Cse
pstr=str;
printf(“\n the string is:”);
while(*pstr!=’\0’)
{
printf(“%c”,*pstr);
pstr++;
}
return 0;
}
In this program, we declare pointer *pstr to show the string on the screen. We then point
the pointer pstr at str. Then we print each character of the string in the while loop. Instead
of using while loop, we could have directly use the function puts
The parameter passed to puts() is a pointer which is the address to which it points to, an
address .thus writing puts(str) i.e means passing the address of str[0].
#include <stdio.h>
void main( )
{
char str[100],*pstr;
int upper=0,lower=0;
printf(“\n Enter the string:”);
gets(str);
pstr=str;
while(*pstr!=’\0’)
{
if(*pstr>=’A’ && *pstr <=’Z’)
upper++;
}
printf(“The total number of capitals is %d”,upper);
printf(“The total number of lower letters is %d”,lower);
1 2 3 4 5 6
102 104 106 108 110 112
Ptr1
3. The address operator returns the address the operand .But when an address operator is
applied to an array name. If gives the same value without the operator.
4. Size of operator
#include <stdio.h>
void main( )
{
int arr[ ]={1,2,3,4,5};
int *ptr;
ptr=arr;
printf(“The size of array=%d”,sizeof(arr)); it give size of array i.e 20
printf(“The size of pointer=%d”,sizeof(ptr)); it gives size of pointer i.e 2
}
Example: E
int (*ptr) (int,int);
It can point to any function ,Which is taking integer argument & return
int data type.
Note :
ptr-name we must place inside the parentheses along with pointer(*). Why we declare
pointer name within the parenthesis.
If we declare pointer name without parenthesis ,it changes the total format, to clear
understand observe the following .
Now, We re –write the above statement without using parenthesis for function pointers
int * ptr (int,int)
In above function, ptr is a function which takes two integer arguments and it returns address of
integer variable (int*) .
When we declare ptr is a normal function, it returns the integer address . its not function pointer.
so, In function pointer we must declare pointer name within parenthesis otherwise compiler
consider as normal function it returns integer address.
When we assign the address of function to pointer , the arguments size,type and return
type should be match, otherwise it gives error i.e incompatible error.
int mul(int,int,int)
(*fp)(10,20) OR fp(10,20)
Example 1:
#include <stdio.h>
int mult(int x,int y,int z);
int add(int x,int y);
int main( )
{
int res1,res2,res3;
int (*ptr) (int,int); function pointer declaration, it is also declare abovethe main also
res1=add(10,20); function call without using function pointers.
res2=mult(2,3,4);
printf(“Before using function pointers %d,%d”,res1,res2);
return n;
}
OUTPUT:
Before using function pointers 30 24
After using function pointer 30
Example 2:
#include<stdio.h>
void display(int n);
void (*fp) (int);
int main()
{
}
void display(int n)
{
printf("\n %d",n);
}
OUTPUT:
The pointer points to the display function
24
10
Example 1:
#include<stdio.h>
void cse4();
void cse5();
void e1cse(void (*csedep) ()); // function declaration with argument as function
int main() pointers
{
e1cse(cse4); // function call here pass the address of cse4() function
e1cse(cse5); // function call here pass the address of cse5() function
return 0;
}
void e1cse(void (*csedep) ()) // function definition
{
csedep(); // calling function pointers
(*csedep)(); // calling function pointers again
}
void cse4()
{
printf("\n Hi....Im CSE4");
}
void cse5()
{
printf("\n Hi....Im CSE5");
}
OUTPUT:
Hi….Im CSE4
Hi….Im CSE4
Hi….Im CSE5
Hi….Im CSE5
maths(div);
return 0;
}
void maths(void (*arthmetic) ())
{
(*arthmetic)();
}
M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 33
PSTC UNIT-V POINTERS
void add()
{
int sum,a,b;
int dif,a,b;
printf("Enter 2 numbers to be sub \n");
scanf("%d%d",&a,&b);
dif=a-b;
printf("The difference of two numbers are:%d \n ",dif);
}
void mul()
{
int mulp,a,b;
printf("Enter 2 numbers to be multiplication\n");
scanf("%d%d",&a,&b);
mulp=a*b;
OUTPUT:
Enter 2 numbers to be add
10
20
The addition of two numbers are : 30
Enter 2 numbers to be sub
24
17
The addition of two numbers are : 7
Enter 2 numbers to be multiplication
6
4
The addition of two numbers are : 24
Enter 2 numbers to be division
169
13
The addition of two numbers are : 13
Printf(“%d”,*num);
}
#include <stdio.h>
int sum(int arr[ ],int size);
void main( )
{
int arr[ ]={1,2,3,4,5};
int total;
total=sum(arr,5);
printf(“Sum of array is %d”,total);
}
int sum(int arr[ ],int size)
{
int i;
int sum1=0;
for(i=0;i<size;i++)
{
sum1+=arr[i];
}
return sum1;
}
#include <stdio.h>
int sum(int *arr,int size);
void main( )
{
int arr[ ]={1,2,3,4,5};
int total;
total=sum(arr,5);
printf(“Sum of array is %d”,total);
}
int sum(int *arr,int size)
{
int i,int sum=0;
for(i=0;i<size;i++)
{
sum+=arr[i];
}
return sum;
}
OUTPUT:
Sum of array is : 15
Syntax:-
int *var_name [array_size];
To read (to scan) and write (to print) array of pointers in to ways :
1. Through Index values.
2. Using pointer arithmetic / modifier
While writing pointers program, we prefer pointer arithmetic to easy to understand, its
no problem to index values also.
Example 1:
#include <stdio.h> 0 1 2 3 4
void main( ) a 10 20 30 40 50
(or)
*(p+i)=a+i; using pointer arithmetic
}
}
for(i=0;i<5;i++)
M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 38
PSTC UNIT-V POINTERS
{
printf(“%d\n”,a[i]); through index value
or
printf(“%d\n”,*(a+i)); pointer arithmetic
or
printf(“%d\n”,*p[i]); pointer through index values
or
printf(“%d\n”,**(p+i)); using pointer arithmetic
}
Example 2:
#include <stdio.h>
int main( )
{ a b c
int a,b,c;
int *ptr[3];
10 20 30
ptr[0]=&a, ptr[1]=&b, ptr[2]=&c; 10254 24325 45321
a=10,b=20,c=30;
printf(“%d\t%d\t%d”,*p[0], *p[1], *p[2]);
10254 24325 45321
*ptr[0]*=30;
*ptr[1] - =5; 1024 1026 1028
*ptr[2]+=6; ptr
printf(“%d,%d,%d”,*p[0], *p[1], *p[2]);
1024
return 0;
}
OUTPUT:
10 20 30
300 15 36
1. malloc( )
2. calloc( )
3. realloc( )
4. free( )
These 4 functions are included in stdlib.h
When we are using dynamic memory allocation, then memory allocated in heap memory.
Syntax:
ptr= (cast_type*) malloc (byte_size)
where ptr is a pointer, malloc( ) function returns the base address of the memory .
Ex:
ptr=(int *)malloc(10*sizeof(int));
#include<stdio.h>
OUTPUT:
#include<stdlib.h> Enter no.of elements you want 4
Enter the index 0 of the array 10
int main() Enter the index 1 of the array 20
Enter the index 2 of the array 30
{ Enter the index 3 of the array 40
The array contains
int n,i; 10 20 30 40
printf("Enter no.of element you want");
exit(0);
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
printf("%d\t",*(arr+i));
free(arr);
return 0;
#include<stdio.h>
int sid;
sid sname smarks
char sname[10]; 102 104 114
(2bytes) (10bytes) (4bytes)
float smarks;
Ptr
}; 102
int main()
{
OUTPUT:
struct student *ptr;
Enter student ID: 1224
ptr=(struct student*)malloc(sizeof(struct student)); Enter student name: Ram
Enter student marks: 8.7
if(ptr==NULL)
Student Details Are:
{ ID NO:1224
NAME: Ram
printf("No storage space"); CGPA:8.7
else
scanf("%d",&ptr->sid);
scanf(" %s",ptr->sname);
scanf("%f",&ptr->smarks);
printf("\n CGPA:%f",ptr->smarks);
Note: When we are using structures with pointer then we have to access the elements with arrow
(->) operator.
This function allocates multiple blocks of request memory with specified size.
Prototype :
Syntax :
where ptr is a pointer, calloc( ) function returns the base address of the memory .
The calloc( ) function successfully completed,it reserves memory, it returns base address.
The calloc( ) function on failure, it reserves not reserve any memory, it returns null
pointer.
Ex:
ptr=(int *)calloc(10*sizeof(int));
In calloc( ), all elements are initialized with 0’s if we not assigned any values.
Example:
OUTPUT:
#include<stdio.h> Enter no.of elements you want 4
Enter the index 0 of the array 10
#include<stdlib.h> Enter the index 1 of the array 20
Enter the index 2 of the array 30
int main() Enter the index 3 of the array 40
The array contains
{
10 20 30 40
int n,i;
arr=(int *)calloc(n,sizeof(int));
102 104 106 108
if(arr==NULL)
Arr
{
102
printf("\n The NO Space in memory
allocation is failed");
exit(0);
else
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
printf("%d\t",*(arr+i));
free(arr);
return 0;
2 In this, default value garbage value if we In this, default value zero. If we Not any
are not initialized any value, values, then the compiler initialized with zero
to all array elements.
3 malloc() function takes single argument calloc() function takes two arguments
4
malloc() is faster than calloc(). calloc() is slow compare to malloc
beacauseof the extra step of initializing the
allocated memory by zero..
Syntax:
ptr = realloc(ptr,newsize)
Prototype:
Ex:
ptr = (int*)realloc(ptr,10)
realloc( ) returns base adreess of the array or structure after decrease or increase memory.
Example:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
char *str;
str=(char*)calloc(5,sizeof(char));
if(str==NULL)
exit(1);
OUTPUT:
} Before realloc():
String=Hello
strcpy(str,"Hi"); String size is modified
Checking the previous data exists or not
printf("Before realloc():\n”); String=Hello
Append new string to previous String
printf("\n String=%s",str);
String=Hello students
str=(char*)realloc(str,10);
Explanation :
if(str==NULL) 1) ptr=(int*)calloc(5,sizeof(char))
{
h i \0 \0 \0
printf("memory could not be allocated");
String =Hi
exit(1);
2) ptr=(int*)realloc(ptr,10)
}
printf("\n String=%s",str);
String");
strcat(str," students");
printf("\n String=%s",str);
free(str);
return 0; }
4.free( ):
Releasing the used space or de-allocate the memory
When a variable is allocated space, then the memory used by that variable is
automatically released by the system.
But when we dynamically allocate memory then it is our responsibility to release
space when it is not required.
This is more important when the storage space is limited.
Syntax : free(ptr)
When ptr is a pointer that has been created by using malloc() or calloc(),where
memory is de-allocated using the free( ).
Dangling Pointers:
The following table shows the all three types of the above
Wild Pointers:
A pointer which has not been initialized to any address (not even NULL) is known as
wild pointers.
If we not initialized any address to pointer then it takes garbage value that is known as
wild pointer.
Ex:
int main()
{
int *ptr; // not initialized with any address .then it takes garbage val, So it a wild pointer.
int x=10;
}
Memory leakage:
Memory leak occurs when programmer create a memory in heap memory and forget to
delete it.
We know that, when we are creating memory using dynamic memory allocation
functions then memory allocated in heap memory. After completion of our program, to
de-allocate memory from heap then we are call free() function end the end of program.
Memory leak is serious issue when a program is repeatedly requesting more memory and
not freeing up. They will exhaust pool of available memory.
Ex:
void arr(int n )
int *p;
p= (int *)malloc(n*sizeof(int));
----------------------
----------------------
----------------------
free(p); To avoid memory leakage we put free function at the end of the program.
}
void main( )
arr(10);
arr(15);
------------
------------
arr(100);
10 bytes 10 bytes
15 bytes 15 bytes
---------------------- ----------------------
---------------------- ----------------------
---------------------- ----------------------
Without using free() in function or program using dynamic memory allocation when we
are call the function again and again the memory full at some point, then occurs the
memory leakage problem.
To overcome this problem we put free( ) at the end of the function then every completion
of a function execution de-allocates its memory by free ( ) function.
Example 1:
Output on cmd: (turbo c)
#include<stdio.h>
>tcc program.c // compile
int main(int argc,char *argv[ ] )
>program //run
{
argument count:1
Printf(“arguments count:%d”,argc);
Example 2:
#include<stdio.h>
int i=0;
if(argc==1){
else {
printf(“List of elements:\n”);
for(i=1;i<agrc;i++)
printf(“%s\n”,argv[i]);
OUTPUT:
>C:/tcc.exe prgm.c > . / a.out ‘R’ 24 2.7 > F: program.exe ‘R’ 24 2.7
R 24 24
24 2.7 2.7
2.7
In devc++, first we
compile the program in
Note:
Command line argument always string type . when we are using addition of two numbers
then it is not possible in string type. so we need to convert argument from string to int.
To solve this program dos.h library provides two functions:
1. atoi ( ) function.
2. atof( ) function.
These two functions included in dos.h library. To use these function we include dos.h
library.
atoi( ) function converts command line arguments string type to integer type.
atof( ) function converts command line arguments string type to float type.
#include<stdio.h>
#include<dos.h>
if(argc>2)
char* s1=argv[1];
char* s2=argv[2];
int x=atoi(s1);
int y=atoi(s2);
printf("sum:%d\n",x+y);
else
return 0;
If we pass more than two arguments its takes only first two values reaming are omits.
We know that, In command line arguments main() function takes two arguments i.e argc
and argv[].
When we pass the arguments through command line, argv[] is can stores the address of
string type.
Command line arguments always string type. all the strings arguments stored in different
locations. argv[] holds the address of the all the arguments where it stores.
Here program name is a first argument it store in argv[0]
To understand memory allocation of command line arguments observe the following
figure.
In the above program , we passed four arguments but total arguments are five because
program name is a 1st argument.
When we trying to access argv[argc] or argv[5] then prints NULL string.