SlideShare a Scribd company logo
Pointer
A pointer is a variable that contains a memory
address of another variable.
A pointer can point to one specific datatype i.e. int,
char, float.
A pointer can have any name that is legal for the
other variable.
It is declared in the same way as other variable but it
always proceeds with * operator.
Pointer declaration syntax:
datatype * variable_name;
Eg: float * y;
Eg: int * p;
Here p signifies the pointer variable and it can store
address of integer variables.
9/6/2022 1
Initializing pointer
Address of the variable can be assigned to a
pointer variable at the time of declaration of the
pointer variable.
int num;
int * ptr = #
or
int num;
int * ptr;
ptr = #
9/6/2022 2
Pointer operators:
There are two special pointer operators and they are *
and &. The operator ‘&’ is called ‘address’ of operand
and the operator ‘*’ is called the ‘value pointed by’
that address.
Reference Operator (&):
The address that locates a variable within memory is
what we call a reference to that variable. This
reference to a variable can be obtained by preceding
the identifier of a variable with ampersand (&) sign
known as reference operator.
9/6/2022 3
Dereference operator (*):
Using a pointer, we can directly access the value stored in
the variable which it points to. To do this we simply have to
proceed the pointer identifier with an asterisk (*) sign
which acts as the reference operator .Thus ‘&’ and ‘*’
operators have complimentary as opposite meaning. A
variable reference with & can be dereference with *.
variable v p
value 10 65552
address 65552 65558
where int v is a variable and * p is a pointer variable.
p = &v;
so,
v and *p are same i.e. 10
&v and p are same i.e. 65552
9/6/2022 4
Sample program:
#include<stdio.h>
main ()
{
int v=10;
printf(" v : %dn", v);
printf("&v : %un", &v);
int *p;
p= &v;
printf(" p : %un" , p);
printf("*p : %dn" , *p);
}
9/6/2022 5
Another sample program:
#include<stdio.h>
main ()
{
int x=15;
printf(" value of x is %dn", x);
printf(" Address of x:%un", &x);
int *ptr;
ptr= &x; //referencing to x
printf(" Address stored in ptr: %un" , ptr);
printf(" value pointed by ptr: %dn" , *ptr); // dereferencing
}
9/6/2022 6
Pointer Arithmetic:
A pointer is an address, which is numeric
value. Therefore, you can perform arithmetic
operations on a pointer just as you can on a
numeric value. There are four arithmetic
operators that can be used on pointers: ++, --,
+ and –.
1. Increment pointer
2. Decrement pointer
9/6/2022 7
Void pointers:
The void type of pointer is a special type of pointer. It represents the
absence of the type so void pointers are the pointers that point to a value
that has no type.
This allow void pointer to point to any data type, from an integer value or
a float to a string of characters.
They have a great limitation: The data pointed by them cannot be directly
dereference and for this reason we will always have to change the type of
void pointers to some others pointer type that points to a specific data
type before dereferencing it. i.e. type casting.
#include<stdio.h>
main () output:
{
void * p, *q ;
int a = 33, b= 44, c;
p= &a;
q= &b;
c= *(int*)p + *(int*)q;
// converting void pointers to a integer using type casting
printf (" a+b = % d" , c);
}
9/6/2022 8
Null pointer:
It is a regular pointer of any pointer type which has a special value that
indicates. It is not pointing to any valid reference or memory address.
int * p;
p = 0;
A null pointer is a value that any pointer may take to represent that it is
pointing to nowhere in the memory address, where a void pointer is
special type of pointer that can point to somewhere without a specific
type.
Pointer to pointer. (Double Pointer)
It is possible to make a pointer to point another pointer thus by creating a
chain of pointer called double pointer
variable p2 p1 Variable
value 5010 5004 2
address 5020 5010 5004
Here, p2 contains the address of pointer variable p1,following declaration
tells compiler that p2 is a double pointer(pointer to pointer)
int * * p2;
9/6/2022 9
#include<stdio.h>
main()
{
int x,*y, **z;
x=5;
y=&x;
z=&y;
printf("value pointed by z is %dn", **z);
printf("value pointed by y is %dn", *y );
printf("value of x is %d", x );
}
Output:
9/6/2022 10
Ways of passing Arguments:
There are two different mechanisms to pass
arguments to the function . They are pass by
value(call by value) and pass by reference(call by
reference/address)
Formal Parameters: The parameters received by
the function.
Actual Parameters: The parameters passed by
the function.
9/6/2022 11
Pass by values
Here, the value of actual parameter will be copied to formal
parameters and these two different parameters store values in
different memory locations.
In call by value, original value can not be changed or modified.
when you passed value to the function it is locally stored by the
function parameter in stack memory location. If you change the
value of function parameter, it is changed for the current function
only but it doesnot change the value of variable inside the caller
method such as main().
The process of passing the actual arguments of a variable is known
as pass by value. In this mechanism, the value of actual arguments
are copied to the formal arguments of the function definition so,
the values of the argument in the calling function are not changed
even they are changed in the called function. It does not allow the
information to be transferred back to the calling function through
the arguments. Thus passing value to the function is restricted to a
one way transfer of information.
9/6/2022 12
// Example pass by value:
#include<stdio.h>
void change(int num) ;
main()
{
int x=100;
printf("Before function call x=%d n", x);
change(x);
printf("After function call x=%d n", x);
}
void change(int num)
{
printf("Before adding value inside function num=%d n",num);
num=num+100;
printf("After adding value inside function num=%d n", num);
}
9/6/2022 13
Pass by References
Here, both the actual and formal parameter refers to the same memory location.
Therefore any changes made to the formal parameters will get reflected to the
actual parameters.
In call by reference, original value is changed or modified because we pass
reference (address). Here, address of the value is passed in the function, so
actual and formal arguments shares the same address space. Hence, any value
changed inside the function, is reflected inside as well as outside the function.
Reference means address and the process of calling a function giving address of
variables as argument is known as passing by reference and pointer variables are
used for this purpose.
In this mechanism, instead of passing x and y, we must pass the address of x and
y(&x, &y). To receive this address we must use pointer variable in the function
definition and declaration instead of normal variables. Here the calling function
with the called function provides the actual memory location inside it. The called
function can perform any operation in the actual memory space so any
manipulation done on the variable from the body of called function will affect on
actual variable declared inside calling function.
This technique can be used to access the variables declared inside the function
from the body of the other function. Also return statement can return more than
one values. In this method, we can pass more than one variable by reference and
effect will be carried inside the calling function.
9/6/2022 14
// Example pass by reference:
#include<stdio.h>
void change(int* num) ;
main()
{
int x=100;
printf("Before function call x=%d n", x);
change(&x);
printf("After function call x=%d n", x);
}
void change(int* num)
{
printf("Before adding value inside function num=%d n",*num);
*num=*num+100;
printf("After adding value inside function num=%d n", *num);
}
9/6/2022 15
//Example: to swap values of two variables
#include <stdio.h>
void swap(int , int );
main ()
{
int x,y;
printf("Enter the values of x and y : " );
scanf("%d%d" ,&x,&y);
printf("Before swap, value of x = %d and y = %d n", x, y );
swap(x,y);
printf("After swap, value of x = %d and y= %d n", x, y);
}
void swap(int p , int q)
{
int temp;
temp =p;
p=q;
q=temp;
}
9/6/2022 16
Here the values of two operands are passed from
the main function to the swap function.
Swap function changes the value of the local
variables p and q which are used to copy the
value sent by the main function but it require to
change the value of x and y. In this pass by value
method, any changes on p does not reflects to x.
similarly, any changes on q does not reflect to y
and return statement cannot return more than
one value at the same time. This is main
disadvantages of pass by value method. And the
advantage is that the original value of the variable
remain unchanged after the function call.
9/6/2022 17
//Example: to swap values of two variables
#include <stdio.h>
void swap(int * , int * );
main ()
{
int x,y;
printf("Enter the values of x and y : " );
scanf("%d%d",&x,&y);
printf("Before swap, value of x = %d and y = %d n", x, y );
swap(&x,&y);
printf("After swap, value of x = %d and y= %d n", x, y);
}
void swap(int * p , int * q)
{
int temp;
temp = *p;
*p = *q;
*q=temp;
}
9/6/2022 18
Here, p recieves the address of x.
i.e. * p =*&(x)
= x
Similarly, q receives the address of y.
i.e. * q =*&(y)
= y
Where the address of variable is passed to the called
function. i.e. the address of x and y are passed to the swap
function. These address are copied to p and q respectively.
Any operation done inside the swap function is actually
done in the memory location pointed by the address. The
swapping done on *p and *q means swapping done on x
and y respectively. Thus the effect is reflected to the calling
function through the operation done inside the called
function(swap function).
The main advantage of this method is that we can carry out
the effect of returning more than one value from the called
function to the calling function. The main disadvantages of
this method is that the original value of the passed variable
does not remain same after the function call.
9/6/2022 19
Returning multiple values from function using pointers:
Example program:
#include <stdio.h>
void calculator(int a,int b, int *sum,int *diff,int *pro,int *div);
main()
{
int x=50,y=10,s,d,p,di;
calculator(x,y,&s,&d,&p,&di);
printf(" Sum= %dn Difference= %dn Product= %dn Quotient= %dn ",
s,d,p,di);
}
void calculator(int a,int b, int *sm,int *diff,int *pro,int *div)
{
*sm=a+b;
*diff=a-b;
*pro=a*b;
*div=a/b;
}
9/6/2022 20
Pointer to an array:
Example:
#include<stdio.h>
int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
int *ptr = arr;
printf("%dn", *ptr);
return 0;
}
9/6/2022 21
Array of pointer
Just like we can declare an array
of int, float or char etc, we can also declare an
array of pointers,
Syntax: datatype *array_name[size];
Example:
int *arrpoint[5];
Here, arrpoint is an array of 5 integer pointers.
It means that this array can hold the address
of 5 integer variables. In other words, you can
assign 5 pointer variables of type pointer
to int to the elements of this array.
9/6/2022 22
Program:
//Array of pointers
#include<stdio.h>
int main()
{
int *arr[5];
int a=10,b=20,c=30,d=40,e=50;
arr[0]=&a;
arr[1]=&b;
arr[2]=&c;
arr[3]=&d;
arr[4]=&e;
int i;
for ( i=0;i<5;i++)
{
printf("value at p[%d]= %d", i,*arr[i]);
}
return 0;
}
9/6/2022 23
Sum of 5 numbers using pointer
#include<stdio.h>
int main()
{
int i, n[5],sum=0;
printf("enter the five numbers");
for ( i=0;i<5;i++)
{
scanf("%d",n+i);
sum =sum+ *(n+i);
}
printf("the sum is %d",sum);
return 0;
}
9/6/2022 24
Dynamic memory allocation
The process of allocating memory at the time of execution
or at the runtime, is called dynamic memory location. Two
types of problem may occur in static memory allocation:
• If number of values to be stored is less than the size of
memory, there would be wastage of memory.
• If we would want to store more values by increase in size
during the execution on assigned size then it fails.
Allocation and release of memory space can be done with
the help of some library function called dynamic memory
allocation function. These library function prototype are
found in the header file, “stdlib.h” where it has been
defined. Pointer has important role in the dynamic
memory allocation to allocate memory.
9/6/2022 25
1. malloc():
This function allocates a size bytes of memory.
It returns a pointer (*) to the first byte or if
there is an error, it returns NULL(to ensure
that the situation is out of memory).
The format is as follows:
(type * ) malloc (size of type);
9/6/2022 26
Program to Allocate memory for n number of elements and print it (using malloc )
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *p;
int n,i;
printf("Enter total number of elements: ");
scanf("%d",&n);
/*allocate memory for n elements dynamically*/
p=(int*)malloc(n*sizeof(int));
if(p==NULL)
{
printf("Insufficient Memory or overflow of memory n");
return 0;
}
printf("Enter %d elements:n",n);
for(i=0; i<n; i++)
{
printf("Enter element of position %d: ",i+1);
scanf("%d",(p+i));
}
printf("The elements are:");
for(i=0; i<n; i++)
printf("%d ",*(p+i));
free(p);
return 0;
}
9/6/2022 27
2. calloc()
Similar principle to malloc ,only difference is that
calloc function is used to allocate multiple block of
memory. Two arguments are there:
• 1st argument specify number of blocks
• 2nd argument specify size of each block.
The Syntax is as follows:
(type * ) calloc (number , size of type);
Example:-
int *p= (int *) calloc(5, 2);
int *p= (int *) calloc(5, size of (int));
Another difference between malloc and calloc is
by default memory allocated by malloc contains
garbage value, where as memory allocated by
calloc is initialized by zero.
9/6/2022 28
Program to Allocate memory for n number of elements and print it (using Calloc )
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *p;
int n,i;
printf("Enter total number of elements: ");
scanf("%d",&n);
/*allocate memory for n elements dynamically*/
p=(int*) calloc(n,sizeof(int));
if(p==NULL)
{
printf("Insufficient Memory or overflow of memory n");
return 0;
}
printf("Enter %d elements:n",n);
for(i=0; i<n; i++)
{
printf("Enter element of position %d: ",i+1);
scanf("%d",(p+i));
}
printf("The elements are:");
for(i=0; i<n; i++)
printf("%d ",*(p+i));
free(p);
return 0;
9/6/2022 29
3. realloc()
If the previously allocated memory is
insufficient or more than required, we can
change the previously allocated memory size
using realloc().The function realloc use to
change the size of the memory block and it
alter the size of the memory block without
loosing the old data, it is called reallocation of
memory. It takes two argument as;
int *ptr=(int *)malloc(size);
int*p=(int *)realloc(ptr, new size);
9/6/2022 30
//Program to Allocate memory for 4 number and reallocate for 5 more elements and print it (using realloc )
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *p;
int i, n;
printf("Initial size of the array is 4n");
p = (int*)malloc(4* sizeof(int));
if(p==NULL)
{
printf("Memory allocation failed") ; exit(1);
}
for(i = 0; i < 4; i++)
{
printf("Enter element at index %d: ", i);
scanf("%d", p+i);
}
printf("nIncreasing the size of the array by 5 elements ...n ");
p = (int*)realloc(p, 9 * sizeof(int));
if(p==NULL)
{
printf("Memory allocation failed n"); exit(1);
}
printf("Enter 5 more integersn");
for(i = 4; i < 9; i++)
{
printf("Enter element at index %d: ", i);
scanf("%d", p+i);
}
printf("Final array: n");
for(i = 0; i < 9; i++)
{
printf("%d ", *(p+i) );
}
free(p);
}
9/6/2022 31
4. free()
Function free() is used to release space allocated
dynamically, the memory released by free() is
made available to heap again. It can be used for
further purpose.
Syntax for free():
int *ptr=(int *)malloc(size);
free(ptr) ;
When program is terminated, memory is released
automatically by the operating system. Even we
don’t free the memory, it doesn’t give error, thus
lead to memory leak. We can’t free the memory,
those didn’t allocated.
9/6/2022 32
WAP to sort n numbers dynamically (i. e. using DMA)
#include <stdio.h>
#include <stdlib.h>
main()
{
int i, j, n, *num, temp;
printf(" How many numbers? n");
scanf("%d", &n);
num=(int *) calloc(n,sizeof(int));
printf("Enter the elements one by one n");
for (i = 0; i < n; i++)
{
scanf("%d", num+i);
}
9/6/2022 33
// sorting begins
for (i = 0; i < n; i++)
{
for (j = i+1; j < n ; j++)
{
if (*(num+i) > *(num+j))
{
temp = *(num+i);
*(num+i) = *(num+j);
*(num+j) = temp;
}
}
}
printf("Sorted array is...n");
for (i = 0; i < n; i++)
{
printf("%dn", *(num+i));
}
}
9/6/2022 34
WAP to sort n numbers
#include <stdio.h>
main()
{
int num[100];
int i, j, n, temp;
printf(" How many numbers? n");
scanf("%d", &n);
printf("Enter the elements one by one n");
for (i = 0; i < n; i++)
{
scanf("%d", &num[i]);
}
9/6/2022 35
// sorting begins
for (i = 0; i < n; i++)
{
for (j = i+1; j < n ; j++)
{
if (num[i] > num[j])
{
temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
}
printf("Sorted array is...n");
for (i = 0; i < n; i++)
{
printf("%dn", num[i]);
}
}
9/6/2022 36
Assignment:7
• Differentiate :
1. Iteration and recursion
2. Call by value and call by address
• WAP to sort n integer values in an array using
pointer.
• WAP using pointer to read in an array of
integers. Next add the element in the array and
display the sum on the screen.
• Explain the term memory leak in brief.
9/6/2022 37
9/6/2022 38

More Related Content

PPTX
2-Concept of Pointers in c programming.pptx
naushigrdcs
 
PPTX
pointers.pptx
s170883BesiVyshnavi
 
PPT
l7-pointers.ppt
ShivamChaturvedi67
 
PPTX
Pointer.pptx
SwapnaliPawar27
 
PPTX
C Programming : Pointers and Strings
Selvaraj Seerangan
 
PPT
pointers CP Lecture.ppt
EC42ShaikhAmaan
 
PPTX
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
KathanPatel49
 
PPTX
Algoritmos e Estruturas de Dados - Pointers
martijnkuipersandebo
 
2-Concept of Pointers in c programming.pptx
naushigrdcs
 
pointers.pptx
s170883BesiVyshnavi
 
l7-pointers.ppt
ShivamChaturvedi67
 
Pointer.pptx
SwapnaliPawar27
 
C Programming : Pointers and Strings
Selvaraj Seerangan
 
pointers CP Lecture.ppt
EC42ShaikhAmaan
 
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
KathanPatel49
 
Algoritmos e Estruturas de Dados - Pointers
martijnkuipersandebo
 

Similar to chapter-7 slide.pptx (20)

PPTX
UNIT 4 POINTERS.pptx pointers pptx for basic c language
wwwskrilikeyou
 
PPT
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Rai University
 
PPTX
UNIT 6structureofcprogrammingforppt.pptx
jayantpatil745
 
PDF
PSPC--UNIT-5.pdf
ArshiniGubbala3
 
PPTX
Pointers
Samsil Arefin
 
PPTX
Pointers
Munazza-Mah-Jabeen
 
PPT
presentation_pointers_1444076066_140676 (1).ppt
georgejustymirobi1
 
PPT
c program.ppt
mouneeshwarans
 
PDF
9. pointer, pointer & function
웅식 전
 
PPTX
Pointers in C Language
madan reddy
 
PDF
Lk module5 pointers
Krishna Nanda
 
PPT
Advanced pointers
Koganti Ravikumar
 
PPT
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handling
Rai University
 
PPT
Btech 1 pic u-5 pointer, structure ,union and intro to file handling
Rai University
 
PPT
pointer, structure ,union and intro to file handling
Rai University
 
PPT
pointer, structure ,union and intro to file handling
Rai University
 
PPT
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
Rai University
 
DOCX
PPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONS
Sitamarhi Institute of Technology
 
PDF
Chapter 13.1.8
patcha535
 
PPT
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
chintuyadav19
 
UNIT 4 POINTERS.pptx pointers pptx for basic c language
wwwskrilikeyou
 
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Rai University
 
UNIT 6structureofcprogrammingforppt.pptx
jayantpatil745
 
PSPC--UNIT-5.pdf
ArshiniGubbala3
 
Pointers
Samsil Arefin
 
presentation_pointers_1444076066_140676 (1).ppt
georgejustymirobi1
 
c program.ppt
mouneeshwarans
 
9. pointer, pointer & function
웅식 전
 
Pointers in C Language
madan reddy
 
Lk module5 pointers
Krishna Nanda
 
Advanced pointers
Koganti Ravikumar
 
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handling
Rai University
 
Btech 1 pic u-5 pointer, structure ,union and intro to file handling
Rai University
 
pointer, structure ,union and intro to file handling
Rai University
 
pointer, structure ,union and intro to file handling
Rai University
 
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
Rai University
 
PPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONS
Sitamarhi Institute of Technology
 
Chapter 13.1.8
patcha535
 
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
chintuyadav19
 
Ad

More from cricketreview (10)

PPTX
FINAL PRESENTATION.pptx
cricketreview
 
PPTX
DREM_chapter 6.pptx
cricketreview
 
PDF
URBAN DESIGN-lecture-4.pdf
cricketreview
 
PPTX
Estimating and costing I Chapter 2.pptx
cricketreview
 
PDF
Chapter 3.4_ Art Deco.pdf
cricketreview
 
PPTX
chapter-6 slide.pptx
cricketreview
 
PPTX
3e- Persian Gardens.pptx
cricketreview
 
PDF
chapter-4 slide.pdf
cricketreview
 
PPTX
Vernacular Architecture of Nepal.pptx
cricketreview
 
PDF
URBAN DESIGN-lecture-6.pdf
cricketreview
 
FINAL PRESENTATION.pptx
cricketreview
 
DREM_chapter 6.pptx
cricketreview
 
URBAN DESIGN-lecture-4.pdf
cricketreview
 
Estimating and costing I Chapter 2.pptx
cricketreview
 
Chapter 3.4_ Art Deco.pdf
cricketreview
 
chapter-6 slide.pptx
cricketreview
 
3e- Persian Gardens.pptx
cricketreview
 
chapter-4 slide.pdf
cricketreview
 
Vernacular Architecture of Nepal.pptx
cricketreview
 
URBAN DESIGN-lecture-6.pdf
cricketreview
 
Ad

Recently uploaded (20)

PDF
dse_final_merit_2025_26 gtgfffffcjjjuuyy
rushabhjain127
 
PDF
Software Testing Tools - names and explanation
shruti533256
 
PDF
Cryptography and Information :Security Fundamentals
Dr. Madhuri Jawale
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PDF
Unit I Part II.pdf : Security Fundamentals
Dr. Madhuri Jawale
 
PDF
July 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
PDF
FLEX-LNG-Company-Presentation-Nov-2017.pdf
jbloggzs
 
PPT
1. SYSTEMS, ROLES, AND DEVELOPMENT METHODOLOGIES.ppt
zilow058
 
PPTX
Information Retrieval and Extraction - Module 7
premSankar19
 
PPTX
FUNDAMENTALS OF ELECTRIC VEHICLES UNIT-1
MikkiliSuresh
 
PPTX
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
PDF
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
PDF
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
PPTX
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
PPTX
22PCOAM21 Session 1 Data Management.pptx
Guru Nanak Technical Institutions
 
PDF
Biodegradable Plastics: Innovations and Market Potential (www.kiu.ac.ug)
publication11
 
PDF
Zero carbon Building Design Guidelines V4
BassemOsman1
 
PDF
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
PDF
Zero Carbon Building Performance standard
BassemOsman1
 
PPTX
database slide on modern techniques for optimizing database queries.pptx
aky52024
 
dse_final_merit_2025_26 gtgfffffcjjjuuyy
rushabhjain127
 
Software Testing Tools - names and explanation
shruti533256
 
Cryptography and Information :Security Fundamentals
Dr. Madhuri Jawale
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
Unit I Part II.pdf : Security Fundamentals
Dr. Madhuri Jawale
 
July 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
FLEX-LNG-Company-Presentation-Nov-2017.pdf
jbloggzs
 
1. SYSTEMS, ROLES, AND DEVELOPMENT METHODOLOGIES.ppt
zilow058
 
Information Retrieval and Extraction - Module 7
premSankar19
 
FUNDAMENTALS OF ELECTRIC VEHICLES UNIT-1
MikkiliSuresh
 
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
22PCOAM21 Session 1 Data Management.pptx
Guru Nanak Technical Institutions
 
Biodegradable Plastics: Innovations and Market Potential (www.kiu.ac.ug)
publication11
 
Zero carbon Building Design Guidelines V4
BassemOsman1
 
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
Zero Carbon Building Performance standard
BassemOsman1
 
database slide on modern techniques for optimizing database queries.pptx
aky52024
 

chapter-7 slide.pptx

  • 1. Pointer A pointer is a variable that contains a memory address of another variable. A pointer can point to one specific datatype i.e. int, char, float. A pointer can have any name that is legal for the other variable. It is declared in the same way as other variable but it always proceeds with * operator. Pointer declaration syntax: datatype * variable_name; Eg: float * y; Eg: int * p; Here p signifies the pointer variable and it can store address of integer variables. 9/6/2022 1
  • 2. Initializing pointer Address of the variable can be assigned to a pointer variable at the time of declaration of the pointer variable. int num; int * ptr = &num; or int num; int * ptr; ptr = &num; 9/6/2022 2
  • 3. Pointer operators: There are two special pointer operators and they are * and &. The operator ‘&’ is called ‘address’ of operand and the operator ‘*’ is called the ‘value pointed by’ that address. Reference Operator (&): The address that locates a variable within memory is what we call a reference to that variable. This reference to a variable can be obtained by preceding the identifier of a variable with ampersand (&) sign known as reference operator. 9/6/2022 3
  • 4. Dereference operator (*): Using a pointer, we can directly access the value stored in the variable which it points to. To do this we simply have to proceed the pointer identifier with an asterisk (*) sign which acts as the reference operator .Thus ‘&’ and ‘*’ operators have complimentary as opposite meaning. A variable reference with & can be dereference with *. variable v p value 10 65552 address 65552 65558 where int v is a variable and * p is a pointer variable. p = &v; so, v and *p are same i.e. 10 &v and p are same i.e. 65552 9/6/2022 4
  • 5. Sample program: #include<stdio.h> main () { int v=10; printf(" v : %dn", v); printf("&v : %un", &v); int *p; p= &v; printf(" p : %un" , p); printf("*p : %dn" , *p); } 9/6/2022 5
  • 6. Another sample program: #include<stdio.h> main () { int x=15; printf(" value of x is %dn", x); printf(" Address of x:%un", &x); int *ptr; ptr= &x; //referencing to x printf(" Address stored in ptr: %un" , ptr); printf(" value pointed by ptr: %dn" , *ptr); // dereferencing } 9/6/2022 6
  • 7. Pointer Arithmetic: A pointer is an address, which is numeric value. Therefore, you can perform arithmetic operations on a pointer just as you can on a numeric value. There are four arithmetic operators that can be used on pointers: ++, --, + and –. 1. Increment pointer 2. Decrement pointer 9/6/2022 7
  • 8. Void pointers: The void type of pointer is a special type of pointer. It represents the absence of the type so void pointers are the pointers that point to a value that has no type. This allow void pointer to point to any data type, from an integer value or a float to a string of characters. They have a great limitation: The data pointed by them cannot be directly dereference and for this reason we will always have to change the type of void pointers to some others pointer type that points to a specific data type before dereferencing it. i.e. type casting. #include<stdio.h> main () output: { void * p, *q ; int a = 33, b= 44, c; p= &a; q= &b; c= *(int*)p + *(int*)q; // converting void pointers to a integer using type casting printf (" a+b = % d" , c); } 9/6/2022 8
  • 9. Null pointer: It is a regular pointer of any pointer type which has a special value that indicates. It is not pointing to any valid reference or memory address. int * p; p = 0; A null pointer is a value that any pointer may take to represent that it is pointing to nowhere in the memory address, where a void pointer is special type of pointer that can point to somewhere without a specific type. Pointer to pointer. (Double Pointer) It is possible to make a pointer to point another pointer thus by creating a chain of pointer called double pointer variable p2 p1 Variable value 5010 5004 2 address 5020 5010 5004 Here, p2 contains the address of pointer variable p1,following declaration tells compiler that p2 is a double pointer(pointer to pointer) int * * p2; 9/6/2022 9
  • 10. #include<stdio.h> main() { int x,*y, **z; x=5; y=&x; z=&y; printf("value pointed by z is %dn", **z); printf("value pointed by y is %dn", *y ); printf("value of x is %d", x ); } Output: 9/6/2022 10
  • 11. Ways of passing Arguments: There are two different mechanisms to pass arguments to the function . They are pass by value(call by value) and pass by reference(call by reference/address) Formal Parameters: The parameters received by the function. Actual Parameters: The parameters passed by the function. 9/6/2022 11
  • 12. Pass by values Here, the value of actual parameter will be copied to formal parameters and these two different parameters store values in different memory locations. In call by value, original value can not be changed or modified. when you passed value to the function it is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only but it doesnot change the value of variable inside the caller method such as main(). The process of passing the actual arguments of a variable is known as pass by value. In this mechanism, the value of actual arguments are copied to the formal arguments of the function definition so, the values of the argument in the calling function are not changed even they are changed in the called function. It does not allow the information to be transferred back to the calling function through the arguments. Thus passing value to the function is restricted to a one way transfer of information. 9/6/2022 12
  • 13. // Example pass by value: #include<stdio.h> void change(int num) ; main() { int x=100; printf("Before function call x=%d n", x); change(x); printf("After function call x=%d n", x); } void change(int num) { printf("Before adding value inside function num=%d n",num); num=num+100; printf("After adding value inside function num=%d n", num); } 9/6/2022 13
  • 14. Pass by References Here, both the actual and formal parameter refers to the same memory location. Therefore any changes made to the formal parameters will get reflected to the actual parameters. In call by reference, original value is changed or modified because we pass reference (address). Here, address of the value is passed in the function, so actual and formal arguments shares the same address space. Hence, any value changed inside the function, is reflected inside as well as outside the function. Reference means address and the process of calling a function giving address of variables as argument is known as passing by reference and pointer variables are used for this purpose. In this mechanism, instead of passing x and y, we must pass the address of x and y(&x, &y). To receive this address we must use pointer variable in the function definition and declaration instead of normal variables. Here the calling function with the called function provides the actual memory location inside it. The called function can perform any operation in the actual memory space so any manipulation done on the variable from the body of called function will affect on actual variable declared inside calling function. This technique can be used to access the variables declared inside the function from the body of the other function. Also return statement can return more than one values. In this method, we can pass more than one variable by reference and effect will be carried inside the calling function. 9/6/2022 14
  • 15. // Example pass by reference: #include<stdio.h> void change(int* num) ; main() { int x=100; printf("Before function call x=%d n", x); change(&x); printf("After function call x=%d n", x); } void change(int* num) { printf("Before adding value inside function num=%d n",*num); *num=*num+100; printf("After adding value inside function num=%d n", *num); } 9/6/2022 15
  • 16. //Example: to swap values of two variables #include <stdio.h> void swap(int , int ); main () { int x,y; printf("Enter the values of x and y : " ); scanf("%d%d" ,&x,&y); printf("Before swap, value of x = %d and y = %d n", x, y ); swap(x,y); printf("After swap, value of x = %d and y= %d n", x, y); } void swap(int p , int q) { int temp; temp =p; p=q; q=temp; } 9/6/2022 16
  • 17. Here the values of two operands are passed from the main function to the swap function. Swap function changes the value of the local variables p and q which are used to copy the value sent by the main function but it require to change the value of x and y. In this pass by value method, any changes on p does not reflects to x. similarly, any changes on q does not reflect to y and return statement cannot return more than one value at the same time. This is main disadvantages of pass by value method. And the advantage is that the original value of the variable remain unchanged after the function call. 9/6/2022 17
  • 18. //Example: to swap values of two variables #include <stdio.h> void swap(int * , int * ); main () { int x,y; printf("Enter the values of x and y : " ); scanf("%d%d",&x,&y); printf("Before swap, value of x = %d and y = %d n", x, y ); swap(&x,&y); printf("After swap, value of x = %d and y= %d n", x, y); } void swap(int * p , int * q) { int temp; temp = *p; *p = *q; *q=temp; } 9/6/2022 18
  • 19. Here, p recieves the address of x. i.e. * p =*&(x) = x Similarly, q receives the address of y. i.e. * q =*&(y) = y Where the address of variable is passed to the called function. i.e. the address of x and y are passed to the swap function. These address are copied to p and q respectively. Any operation done inside the swap function is actually done in the memory location pointed by the address. The swapping done on *p and *q means swapping done on x and y respectively. Thus the effect is reflected to the calling function through the operation done inside the called function(swap function). The main advantage of this method is that we can carry out the effect of returning more than one value from the called function to the calling function. The main disadvantages of this method is that the original value of the passed variable does not remain same after the function call. 9/6/2022 19
  • 20. Returning multiple values from function using pointers: Example program: #include <stdio.h> void calculator(int a,int b, int *sum,int *diff,int *pro,int *div); main() { int x=50,y=10,s,d,p,di; calculator(x,y,&s,&d,&p,&di); printf(" Sum= %dn Difference= %dn Product= %dn Quotient= %dn ", s,d,p,di); } void calculator(int a,int b, int *sm,int *diff,int *pro,int *div) { *sm=a+b; *diff=a-b; *pro=a*b; *div=a/b; } 9/6/2022 20
  • 21. Pointer to an array: Example: #include<stdio.h> int main() { int arr[5] = { 1, 2, 3, 4, 5 }; int *ptr = arr; printf("%dn", *ptr); return 0; } 9/6/2022 21
  • 22. Array of pointer Just like we can declare an array of int, float or char etc, we can also declare an array of pointers, Syntax: datatype *array_name[size]; Example: int *arrpoint[5]; Here, arrpoint is an array of 5 integer pointers. It means that this array can hold the address of 5 integer variables. In other words, you can assign 5 pointer variables of type pointer to int to the elements of this array. 9/6/2022 22
  • 23. Program: //Array of pointers #include<stdio.h> int main() { int *arr[5]; int a=10,b=20,c=30,d=40,e=50; arr[0]=&a; arr[1]=&b; arr[2]=&c; arr[3]=&d; arr[4]=&e; int i; for ( i=0;i<5;i++) { printf("value at p[%d]= %d", i,*arr[i]); } return 0; } 9/6/2022 23
  • 24. Sum of 5 numbers using pointer #include<stdio.h> int main() { int i, n[5],sum=0; printf("enter the five numbers"); for ( i=0;i<5;i++) { scanf("%d",n+i); sum =sum+ *(n+i); } printf("the sum is %d",sum); return 0; } 9/6/2022 24
  • 25. Dynamic memory allocation The process of allocating memory at the time of execution or at the runtime, is called dynamic memory location. Two types of problem may occur in static memory allocation: • If number of values to be stored is less than the size of memory, there would be wastage of memory. • If we would want to store more values by increase in size during the execution on assigned size then it fails. Allocation and release of memory space can be done with the help of some library function called dynamic memory allocation function. These library function prototype are found in the header file, “stdlib.h” where it has been defined. Pointer has important role in the dynamic memory allocation to allocate memory. 9/6/2022 25
  • 26. 1. malloc(): This function allocates a size bytes of memory. It returns a pointer (*) to the first byte or if there is an error, it returns NULL(to ensure that the situation is out of memory). The format is as follows: (type * ) malloc (size of type); 9/6/2022 26
  • 27. Program to Allocate memory for n number of elements and print it (using malloc ) #include <stdio.h> #include <stdlib.h> int main() { int *p; int n,i; printf("Enter total number of elements: "); scanf("%d",&n); /*allocate memory for n elements dynamically*/ p=(int*)malloc(n*sizeof(int)); if(p==NULL) { printf("Insufficient Memory or overflow of memory n"); return 0; } printf("Enter %d elements:n",n); for(i=0; i<n; i++) { printf("Enter element of position %d: ",i+1); scanf("%d",(p+i)); } printf("The elements are:"); for(i=0; i<n; i++) printf("%d ",*(p+i)); free(p); return 0; } 9/6/2022 27
  • 28. 2. calloc() Similar principle to malloc ,only difference is that calloc function is used to allocate multiple block of memory. Two arguments are there: • 1st argument specify number of blocks • 2nd argument specify size of each block. The Syntax is as follows: (type * ) calloc (number , size of type); Example:- int *p= (int *) calloc(5, 2); int *p= (int *) calloc(5, size of (int)); Another difference between malloc and calloc is by default memory allocated by malloc contains garbage value, where as memory allocated by calloc is initialized by zero. 9/6/2022 28
  • 29. Program to Allocate memory for n number of elements and print it (using Calloc ) #include <stdio.h> #include <stdlib.h> int main() { int *p; int n,i; printf("Enter total number of elements: "); scanf("%d",&n); /*allocate memory for n elements dynamically*/ p=(int*) calloc(n,sizeof(int)); if(p==NULL) { printf("Insufficient Memory or overflow of memory n"); return 0; } printf("Enter %d elements:n",n); for(i=0; i<n; i++) { printf("Enter element of position %d: ",i+1); scanf("%d",(p+i)); } printf("The elements are:"); for(i=0; i<n; i++) printf("%d ",*(p+i)); free(p); return 0; 9/6/2022 29
  • 30. 3. realloc() If the previously allocated memory is insufficient or more than required, we can change the previously allocated memory size using realloc().The function realloc use to change the size of the memory block and it alter the size of the memory block without loosing the old data, it is called reallocation of memory. It takes two argument as; int *ptr=(int *)malloc(size); int*p=(int *)realloc(ptr, new size); 9/6/2022 30
  • 31. //Program to Allocate memory for 4 number and reallocate for 5 more elements and print it (using realloc ) #include<stdio.h> #include<stdlib.h> int main() { int *p; int i, n; printf("Initial size of the array is 4n"); p = (int*)malloc(4* sizeof(int)); if(p==NULL) { printf("Memory allocation failed") ; exit(1); } for(i = 0; i < 4; i++) { printf("Enter element at index %d: ", i); scanf("%d", p+i); } printf("nIncreasing the size of the array by 5 elements ...n "); p = (int*)realloc(p, 9 * sizeof(int)); if(p==NULL) { printf("Memory allocation failed n"); exit(1); } printf("Enter 5 more integersn"); for(i = 4; i < 9; i++) { printf("Enter element at index %d: ", i); scanf("%d", p+i); } printf("Final array: n"); for(i = 0; i < 9; i++) { printf("%d ", *(p+i) ); } free(p); } 9/6/2022 31
  • 32. 4. free() Function free() is used to release space allocated dynamically, the memory released by free() is made available to heap again. It can be used for further purpose. Syntax for free(): int *ptr=(int *)malloc(size); free(ptr) ; When program is terminated, memory is released automatically by the operating system. Even we don’t free the memory, it doesn’t give error, thus lead to memory leak. We can’t free the memory, those didn’t allocated. 9/6/2022 32
  • 33. WAP to sort n numbers dynamically (i. e. using DMA) #include <stdio.h> #include <stdlib.h> main() { int i, j, n, *num, temp; printf(" How many numbers? n"); scanf("%d", &n); num=(int *) calloc(n,sizeof(int)); printf("Enter the elements one by one n"); for (i = 0; i < n; i++) { scanf("%d", num+i); } 9/6/2022 33
  • 34. // sorting begins for (i = 0; i < n; i++) { for (j = i+1; j < n ; j++) { if (*(num+i) > *(num+j)) { temp = *(num+i); *(num+i) = *(num+j); *(num+j) = temp; } } } printf("Sorted array is...n"); for (i = 0; i < n; i++) { printf("%dn", *(num+i)); } } 9/6/2022 34
  • 35. WAP to sort n numbers #include <stdio.h> main() { int num[100]; int i, j, n, temp; printf(" How many numbers? n"); scanf("%d", &n); printf("Enter the elements one by one n"); for (i = 0; i < n; i++) { scanf("%d", &num[i]); } 9/6/2022 35
  • 36. // sorting begins for (i = 0; i < n; i++) { for (j = i+1; j < n ; j++) { if (num[i] > num[j]) { temp = num[i]; num[i] = num[j]; num[j] = temp; } } } printf("Sorted array is...n"); for (i = 0; i < n; i++) { printf("%dn", num[i]); } } 9/6/2022 36
  • 37. Assignment:7 • Differentiate : 1. Iteration and recursion 2. Call by value and call by address • WAP to sort n integer values in an array using pointer. • WAP using pointer to read in an array of integers. Next add the element in the array and display the sum on the screen. • Explain the term memory leak in brief. 9/6/2022 37