0% found this document useful (0 votes)
54 views87 pages

Unit - IV - Pointers

Pointers allow accessing and manipulating variables indirectly through memory addresses. There are 3 key points: 1. A pointer variable stores the address of another variable. Pointer variables must be declared with a data type and an asterisk, like "int *ptr". 2. The ampersand (&) operator returns the address of its operand. To initialize a pointer variable to point to another variable, the address of the variable is assigned to the pointer, like "ptr = &var". 3. The dereference operator (*) accesses the value of the variable at the address stored in the pointer, like "*ptr". Pointers allow passing arguments by reference and returning multiple values from functions.

Uploaded by

Moni
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)
54 views87 pages

Unit - IV - Pointers

Pointers allow accessing and manipulating variables indirectly through memory addresses. There are 3 key points: 1. A pointer variable stores the address of another variable. Pointer variables must be declared with a data type and an asterisk, like "int *ptr". 2. The ampersand (&) operator returns the address of its operand. To initialize a pointer variable to point to another variable, the address of the variable is assigned to the pointer, like "ptr = &var". 3. The dereference operator (*) accesses the value of the variable at the address stored in the pointer, like "*ptr". Pointers allow passing arguments by reference and returning multiple values from functions.

Uploaded by

Moni
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/ 87

UNIT - IV

POINTERS
• Topics to be covered

Pointers

 Pointer Constants
 Pointer Values
 Pointer Variables
 Accessing Variables Through Pointers
 Pointer Declaration and Definition
 Declaration versus Redirection
 Initialization of Pointer Variables
 Pointer for inter function communication
 Pointer to pointers.
A pointer is a constant or variable that contains an address that can be used to access data. Pointers
are built on the basic concept of pointer constants.
Character Constants and Variables
S.Durga Devi,CSE,CBIT

Pointer Constants
 An address expression(unary expression) consists of an
ampersand (&) and a variable name.
 The address operator (&) extracts the address for a variable.
 The address operator format is: &variable_name

Print Character Addresses


Pointer variable can store the address of a
variable.

Pointer Variable
Multiple Pointers to a Variable
Pointers
Pointers provides the way of accessing the variable without referring to the variable directly.
Address of the variable.
You can refer to a variable indirectly using the address of the variable.
Pointer variable
- is a variable which holds the memory address of another variable.
- does not store the value.

Uses of Pointers

Call by reference
Returns more than one value from a function indirectly.
Pass arrays and strings more conveniently from one function to another function.
Easy manipulation of arrays.
Create complex data structures like linked lists and binary tree.
Compile faster.
Develop efficient code (reduces length and complexity)than other derived data types such
arrays.
As we know, computers use their memory for storing the instructions of a program, as well as the values
of the variables that are associated with it.
The computer’s memory is a sequential collection of ‘storage cells’.
Each cell can hold one byte of information, has a unique number associated with it called as ‘address’.
The computer addresses are numbered consecutively, starting from zero. The last address depends on
the memory size.
Let us assume the size of the memory is 64K then,
The total memory locations = 64K
= 64 * 1K
= 64 * 1024 bytes
= 65536 bytes (locations)
So, here the last address is 65535(started with 0).
Whenever we declare a variable, the system allocates , an appropriate location to hold the value of the
variable somewhere in the memory,.
Consider the following declaration,
int i=10;
This declaration tells the C compiler to perform the following activities:
Reserve space in the memory to hold the integer value.
Associate the name i with this memory location.
Store the value 10 at this location.
We can represent i’s location in the memory by the following memory map:

i Variable name
10 Value at location
65524 Address of variable
 A variable Which holds the address of some other variable is called pointer
variable.
 A pointer variable should always contain the address only.
 The * Operator (asterisk)
 It is called as ‘Value at address’ operator. It returns the value stored at a
particular address.
 It is also Known as Indirection or Dereferencing Operator.
accessing a variable through pointer
the following sequence of operations have to be performed ,to use pointers.
1. Declare an ordinary variable.
2. Declare a pointer variable.
3. Initialize a pointer variable (Provide link between pointer variable and
ordinary variable).
4. Access the value of a variable using pointer variable.
5. The Indirection and Address Operators are the inverse of each other.
Declaring the Pointer

the syntax for declaring a pointer variable

data type *ptr_name;

This tells the compiler three things about the variable ptr_name.
1.The asterisk(*) tells that the variable ptr_name is a pointer variable.
2.ptr_name needs a memory location.
3.ptr_name points to a variable of type data type.
For example,
int *p;
p is a pointer variable of type integer, which stored the address of the
integer variable. It doesn’t mean the p is going to store the integer value
DECLARING POINTER VARIABLES
UNINITIALIZED POINTERS
3. Initialize a pointer variable
• Once a pointer variable has been declared, it can be made to point to a variable using
statement such as
ptr_name=&var;

Which cause ptr_name to point to var.Now ptr_name contains


the address of var. This is known as pointer initialization.
Pointer should not be used before its initialization.
• Access the value of a variable using pointer variable.

*ptr_name
DEMONSTRATE THE USE OF POINTERS
i pi
10 8342
8342 8338

output

*(&i) placing indirection operator before pointer- deferencing


pointer
i c f
10 A 15.67
6432 4562 8765
ADDING TWO POINTERS
Demonstrate Pointer Flexibility
Using One Pointer for Many Variables
Using One Pointer for Many Variables
S.Durga Devi,CSE,CBIT

One Variable with Many Pointers


S.Durga Devi,CSE,CBIT
Using A Variable with Many Pointers
Using A Variable with Many Pointers
POINTERS AS PARAMETERS TO FUNCTION

. call by reference-
In this method the addresses of the actual arguments in the
calling function are copied into the formal arguments of the
called function.
Whatever changes made in the formal arguments in the called
function can have effect to the value of the actual arguments in
the calling function.
Write a c program to swapping of two numbers using call by
value and call by reference.
Call by value Call by reference
void swap(int,int); void swap(int,int);
void main() void main()
{ {
int a=10,b=20; int a=10,b=20;
swap(a,b); swap(&a,&b);
printf(“\n a and b values after printf(“\n and b values after swapping”);
swapping”); printf(“\n a=%d b=%d”,a,b);
printf(“\na=%d,b=%d”,a,b); }//main
}//main //function definition
// function definition swap(int *x,int *y)
swap(int x,int y) {
{ int temp;
int temp; temp=*x;
temp=x; *x=*y;
x=y; *y=temp;
y=temp; }//swap
printf(“\nx=%d,y=%d”,x,y);
}//swap()
An Unworkable Exchange
Exchange Using Pointers
RETURN MORE THAN ONE VALUE FROM A
FUNCTION
main()
{ float r, area, perimeter;
float compute(float, float*);
printf(“enter r value”);
scanf(“%f”,&r);
area=compute(r,&perimeter);
printf(“area=%f” area);
printf(“perimeter=%f”perimeter);
}
float compute(float r, float *p)
{
float a;
a=(float)3.14*r*r;
*p=(float)3.14*r*r;
return a;}
POINTERS TO POINTER
• Pointers points to pointers, in turn points to data.
• Add an (*) at each level of reference.
Pointers to Pointers
Using Pointers to Pointers
Using pointers to pointers
S.Durga Devi,CSE,CBIT
Using pointers to pointers
Using pointers to pointers
Demonstrate Size of Pointers
Demonstrate Size of Pointers
Demonstrate Size of Pointers
Arrays and pointers – Pointer arithmetic and arrays,
Memory allocation functions – static and dynamic
memory allocation, array of pointers.
ARRAYS AND POINTERS
#include<stdio.h>
void main()
{
int a[]={1,2,3,4,5};
Printf(“%u %u”, a,&a[0]);
}
a and &a[0] both gives the address of the first element of an
array
Arrays and Pointers

The name of an array is a pointer constant to


the first element.

Because the array’s name is a pointer constant,


its value cannot be changed.

Since the array name is a pointer constant to


the first element, the address of the first
element and the name of the array both
represent the same location in memory.
Pointers to Arrays
same
a &a[0]
a is a pointer only to the first element—not the whole array.

To access an array, any pointer to the first element can be used instead of the
name of the array.
Dereference of Array Name
Array Names as Pointers
Multiple Array Pointers
ARRAYS AND POINTERS
Print the elements of the array using Print array elements using pointers
subscript void main()
void main() {
{ int arr[]={10,20,30,40,50};
int arr[]={10,20,30,40,50}; int i,*j;
int i; j=&arr[0];//assign address of 0th element
for(i=0;i<5;i++) for(i=0;i<5;i++)
{ {
printf(“\n address =%u”,&arr[i]); printf(“\n address =%u”,j]);
printf(“ value =%d”,arr[i]); printf(“ value =%d”,*j);
} j++;
assume that the address of zeroth element }
is 1000

Note- accessing the elements with pointer variable


is much faster than the accessing the array elements
with the subscript.
Pointer Arithmetic and Arrays
Besides indexing, programmers use another powerful
method of moving through an array: pointer arithmetic.

Pointer arithmetic offers a restricted set of arithmetic


operators for manipulating the addresses in pointers.
POINTER ARITHMETIC
Following arithmetic operations can apply on pointers
1. Addition or subtraction with integers
2. Subtraction of two pointers
3. Comparing pointers
• The following operations should not be applied on the pointers.
1. addition of two pointers.
2. multiplication of a pointer with a constant
3. division of a pointer with a constant.
1. ADDING AND SUBTRACTION WITH
INTEGERS
 Whenever a pointer is incremented it points to the immediately next
location of its type.
 When an integer pointer is incremented it points to an address two
locations after the current location.(if integer takes two bytes).
 If pointer variable is decremented it points to the earlier locations by its
type.
Given pointer, p, p ± n is a pointer to the
value n elements away.

Pointer Arithmetic
Pointer Arithmetic and Different Types
ARITHMETIC OPERATIONS ON POINTERS
void main()
{
int i=3,*x;
float j=1.5,*y;
char k=‘c’,*z;
x=&i;
y=&j;
z=&k;
printf(“\n address in x= address in x=65524
%u”,x); address in y=65520
printf(“\n address in y=%u’,y); address in z=65519
printf(“\n address in z= %u,z);
x++;
y++;
z++; address in x=65526
printf(“\n address in x=%u”,x); address in y=65524
printf(“\n address in y=%u’,y); address in z=65520
printf(“\n address in z= %u,z);
}
• 1. add number to a pointer. 2. Subtract a number from a pointer
void main() void main()
{ {
int i=10,*j; int i=10,*j;
j=&i; j=&i;
printf(“\nsize of i=%d”,sizeof(i)); printf(“j value=%u”,j);
printf(“\nj value=%u”,j); j=j-1;
j=j+1; printf(“j value=%u”,j);
printf(“\nj value after adding=%u”,j); j=j-3;
j=j+3; printf(“j value=%u”,j);
printf(“j value after adding 3=%u”,j);

OUTPUT
size of i=4
j value=3215886008
j value after adding=3215886012
j value after adding 3=3215886024
3. Subtraction of one pointer from another pointer
 one pointer can be subtracted from the other
pointer both must be point to elements of the same
array.
 The resultant value would be the number of elements
separating the corresponding array elements.
void main()
{
int a[]={10,20,30,40,50};
int *i,*j;
i=&a[1];
j=&a[4];
printf("\nvalue of i=%u",i);
Out put
printf("\nvalue of j=%u",j);
3 30
printf("\n%d %d",j-i,*j-*i);
}
S.Durga Devi,CSE,CBIT

• 4. comparison of two pointer variables.


 pointer variables can be compared if both the
pointer variables point to the objects of the same
data type.
 comparisions can be useful when both pointer
void main()
variables
{ point to elements of the same array.
int a[]={10,20,30,40,50,60};
int i,*p;
for(p=a;p<=a+4;p++) Output
printf(“ %d”,*p);
}//main 10 20 30 40 50
S.Durga Devi,CSE,CBIT

• The following operations should not be applied on the


pointers.
1. addition of two pointers.

int x=10,y=20;
int *i,*j;
i=&x;
j=&y;
printf(“%d”,i+j);

2. multiplication of a pointer with a constant


3. division of a pointer with a constant.
PASSING ARRAYS AS ARGUMENTS TO FUNCTIONS
• We can pass array elements as arguments to the called function in two ways
• 1. pass individual array element at a time.
• 2. pass the entire array at a time
• 1. passing individual array elements.
• we can pass individual array elements to the called functions by either call by
value or call by reference. Call by reference
Call by value void main()
{
void main() int i;
{ int arr[]={10,20,30,40,50};
int i; for(i=0;i<5;i++)
int display(&arr[i]);
arr[]={10,20,30,40,50}; getch();
for(i=0;i<5;i++) }//main
display(arr[i]); display( int *x)
getch(); { printf(“%d”,*x);
}//main }//display
2. PASS THE ENTIRE ARRAY AT A TIME

• Fixed length array- the size of the array is known when the
program is written. int arr[10];
• Variable length array- the size of the array is known when the
program is run. int arr[n];

• If u want to pass the fixed length array as argument to the called


function, simply pass the array name to called function.
void display(int x[]); void display(int x[])
void main() {
{ int i;
int arr[5]={10,20,30,40,50}; for(i=0;i<5;i++)
display(arr); {
printf(" %d",x[i]);
}//main }//for
}//display()
• In variable length array we have to pass array name as well as
size of the array to the called function.
void display(int arr[],int size); void display(int arr[],int size)
void main() {
{ int i;
int a[10]; for(i=0;i<size;i++)
int n,i; printf(" %d",arr[i]);
clrscr(); }
printf("\n enter the size of the array");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
Note- In c, the name of an array gives the
display(a,n);
address of the first element in the array
getch();
}//main
The following notations are same:
• arr[i]
• *( arr + i ) void main()
{
• *( i + arr ) int arr[]={10,20,30,40};
int i;
• i[arr] for(i=0;i<4;i++)
{
printf(“\naddress=%u”,&arr[i]);
printf(“value=%d %d %d
%d”,arr[i],*(arr+i),*(i+arr),i[arr]);
}//for
}//main
POINTERS AND 2-DIMENSIONAL ARRAYS

• /* Demo: 2-D array is an array of arrays */


main( )
{
s[2][1]
int s[4][2] = {
* ( s[2] + 1 )
{ 1234, 56 }, • (*(s+2)+1)
{ 1212, 33 }, • all the statements
are same they
{ 1434, 80 },
prints values.
{ 1312, 78 }
};
int i ;
for ( i = 0 ; i <= 3 ; i++ )
printf ( "\nAddress of %d th 1-D array = %u", i, s[i] ) ;}
main( ) for ( i = 0 ; i <= 3 ; i++ )
{ {
int s[4][2] = { printf ( "\n" ) ;
for ( j = 0 ; j <= 1 ; j++ )
{ 1234, 56 }, printf ( "%d ", *( *( s + i ) + j ) ) ;
{ 1212, 33 }, }
{ 1434, 80 }, }
{ 1312, 78 } And here is the output...
}; 1234 56
1212 33
int i, j ; 1434 80
1312 78
ARRAY OF POINTERS

 int a[10];- array of 10 integers

 float x[10];- array of 10 real numbers


 char ch[10];- array of 10 characters.
 array of pointers- nothing but collection of addresses.
Addresses of the individual variables are stored into an array or
address of the array elements.
 syntax Data_type *array_name[size];
example
int *arr[10];// array of 10 integer pointers
float *x[10];// array of 10 real number pointers
ARRAY OF POINTERS
void main( )
{
int *arr[4] ; /* array of integer pointers */
int i = 31, j = 5, k = 19, l = 71, m ;
arr[0] = &i ;
arr[1] = &j ;
arr[2] = &k ;
arr[3] = &l ;
for ( m = 0 ; m <= 3 ; m++ )
printf ( "%d ", * ( arr[m] ) ) ;
}
SEE THE DIFFERENCES BELOW

• int a[10];- it is an array of 10 integers


• int *a[10];- it is an array of 10 integer pointers
• int (*a)[10];- it is a pointer to an array of 10 integers.
Memory Allocation Functions
How do you allocate memory for an object?
Two techniques used for memory allocation.
1. Static memory allocation 2. Dynamic Memory allocation

 Memory Usage
 Static Memory Allocation
 Dynamic Memory Allocation
 Memory Allocation Functions
 Releasing Memory (free)

70
Memory Allocation
71
MEMORY ALLOCATION METHODS
72

• Memory allocation two types.


1. Static memory allocation
2. Dynamic memory allocation.
1. Static memory allocation- the process of allocating
memory during compile time of a program.
2. Dynamic memory allocation- the process of
allocating memory during run time of a program.
To access data in dynamic memory therefore, we must
use a pointer
S.Durga Devi,CSE,CBIT

73 • There are 4 dynamic memory allocation function which are


available in the stdlib.h header file
1. malloc()
2. calloc()
3. realloc()
4. free()
malloc(), calloc(), realloc() used for the memory allocation
free()- de allocate the memory if it is no longer needed.
Memory Management Functions
74
The process of allocating memory at runtime is known as dynamic memory allocation.
Library routines known as memory management functions are used for allocating and
freeing memory during execution of a program. These functions are defined
in stdlib.h header file.
Function Description
malloc() allocates requested size of bytes and returns a void
pointer pointing to the first byte of the allocated space

calloc() allocates space for an array of elements, initialize them to


zero and then returns a void pointer to the memory

free releases previously allocated memory


realloc modify the size of previously allocated space
Memory Allocation Process
Global variables, static variables and program instructions get their memory in permanent storage area
whereas local variables are stored in a memory area called Stack.
The memory space between these two region is known as Heap area. This region is used for dynamic
memory allocation during execution of the program. The size of heap keep changing.
malloc()- block of memory
 Allocates block memory which contains the number of bytes specified as its parameter
 It returns a pointer of type void to the first byte of the allocated memory, even the
allocated memory is not initialized.
 This means that we can assign it to any type of pointer.
 Syntax

ptr= (cast-type*)malloc(size);
-If you want to allocate the memory dynamically to an integer object
- ptr= ( int *)malloc(sizeof(int));
- if requested memory is available malloc( ) returns a pointer which contains the first
address of the allocated block of memory.
- otherwise if the requested memory is not available in the heap malloc() returns NULL values.

77
78
CALLOC()- ALLOCATES MULTIPLE BLOCK OF
MEMORY

• The calloc function is primarily used to allocate memory for arrays.


• Allocated memory initialized to zero.
• Remaining all are same as malloc()

Ptr=(cast_type*)calloc(n,size);
79

3. realloc()- this function is used to alter the size of


memory which has been already allocated.
 syntax
Realloc (ptr, newsize);
realloc
80
Releasing of memory (free)

When memory locations are allocated by malloc, calloc, or realloc


are no longer needed, they should be deallocated using the
predefined function free.

It is an error to free memory with a null pointer.

It is also a potential error to refer to memory after it has been


released.

The function declaration statement for free is shown below:


void free (void* ptr);

81
The first one releases a single element, allocated with malloc, back to
heap and second one releases 200 elements (allocated with calloc) back
to heap.
Note: It is not the pointers that are being released but rather what they
point to.

Freeing Memory
82
83
84
Program using malloc and free

// Program to calculate the sum of n numbers entered by the user


#include <stdio.h>
#include <stdlib.h>
int main()
{ int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int)); // if memory cannot be allocated
if(ptr == NULL)
{ printf("Error! memory not allocated.");
exit(0); }
printf("Enter elements: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum); // deallocating the memory
free(ptr);
return 0; }
PROGRAM USING CALLOC() AND FREE()

// Program to calculate the sum of n numbers entered by the use


r #include <stdio.h>
#include <stdlib.h>
int main()
{ int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) calloc(n, sizeof(int));
if(ptr == NULL)
{ printf("Error! memory not allocated.");
exit(0); }
printf("Enter elements: ");
for(i = 0; i < n; ++i)
{ scanf("%d", ptr + i);
sum += *(ptr + i); }
printf("Sum = %d", sum);
free(ptr);
return 0; }
#include <stdio.h>
#include <stdlib.h>
int main()
{ int *ptr, i , n1, n2;
printf("Enter size: ");
scanf("%d", &n1);
ptr = (int*) malloc(n1 * sizeof(int));
printf("Addresses of previously allocated memory: ");
for(i = 0; i < n1; ++i)
printf("%u\n",ptr + i);
printf("\nEnter the new size: ");
scanf("%d", &n2);
// rellocating the memory
ptr = realloc(ptr, n2 * sizeof(int));
printf("Addresses of newly allocated memory: ");
for(i = 0; i < n2; ++i)
printf("%u\n", ptr + i);
free(ptr);
return 0;
}
When you run the program, the output will be:
Enter size: 2
Addresses of previously allocated memory:26855472 26855476
Enter the new size: 4
Addresses of newly allocated memory:26855472 26855476 26855480 26855484

You might also like