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

Chapter-7 Slide

A pointer is a variable that stores the memory address of another variable. Pointers are declared with a datatype followed by an asterisk (*), such as int *ptr. The ampersand (&) operator returns the memory address of a variable, which can be assigned to a pointer variable. The dereference operator (*) accesses the value at the memory address stored in the pointer. Pointers allow passing arguments by reference, where changes made to the pointer variable are reflected in the original variable.

Uploaded by

cricket review
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
160 views

Chapter-7 Slide

A pointer is a variable that stores the memory address of another variable. Pointers are declared with a datatype followed by an asterisk (*), such as int *ptr. The ampersand (&) operator returns the memory address of a variable, which can be assigned to a pointer variable. The dereference operator (*) accesses the value at the memory address stored in the pointer. Pointers allow passing arguments by reference, where changes made to the pointer variable are reflected in the original variable.

Uploaded by

cricket review
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

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.
02/07/2023 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 = #
02/07/2023 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.
 
02/07/2023 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 *.
variablev p
value10 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

02/07/2023 4
Sample program:

#include<stdio.h>
main ()
{
int v=10;
printf(" v : %d\n", v);
printf("&v : %u\n", &v);
int *p;
p= &v;
printf(" p : %u\n" , p);
printf("*p : %d\n" , *p);
}

02/07/2023 5
Another sample program:

#include<stdio.h>
main ()
{
int x=15;
printf(" value of x is %d\n", x);
printf(" Address of x:%u\n", &x);
int *ptr;
ptr= &x; //referencing to x
printf(" Address stored in ptr: %u\n" , ptr);
printf(" value pointed by ptr: %d\n" , *ptr); // dereferencing
}
02/07/2023 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

02/07/2023 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);
02/07/2023 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
variablep2p1Variable
value5010 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;
02/07/2023 9
#include<stdio.h>
main()
{
int x,*y, **z;
x=5;
y=&x;
z=&y;
printf("value pointed by z is %d\n", **z);
printf("value pointed by y is %d\n", *y );
printf("value of x is %d", x );
}

Output:

02/07/2023 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.

02/07/2023 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.

02/07/2023 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);
}
02/07/2023 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.

02/07/2023 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);
}
02/07/2023 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;
02/07/2023 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.
02/07/2023 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;
02/07/2023 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.
02/07/2023 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= %d\n Difference= %d\n Product= %d\n Quotient= %d\n ", 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;
}02/07/2023 20
Pointer to an array:
Example:
#include<stdio.h>
int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
int *ptr = arr;
printf("%d\n", *ptr);
return 0;
}
02/07/2023 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.
02/07/2023 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;
}

02/07/2023 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;
}

02/07/2023 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.
02/07/2023 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);

02/07/2023 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;
}
02/07/2023 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.
02/07/2023 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;
02/07/2023 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);

02/07/2023 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 4\n");
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 integers\n");
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);
}02/07/2023 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.
02/07/2023 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);
}
02/07/2023 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("%d\n", *(num+i));
}
}

02/07/2023 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]);
}

02/07/2023 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("%d\n", num[i]);
}
}

02/07/2023 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.
02/07/2023 37
02/07/2023 38

You might also like