Unit - IV - Pointers
Unit - IV - Pointers
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
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
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;
*ptr_name
DEMONSTRATE THE USE OF POINTERS
i pi
10 8342
8342 8338
output
. 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
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
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
int x=10,y=20;
int *i,*j;
i=&x;
j=&y;
printf(“%d”,i+j);
• 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];
Memory Usage
Static Memory Allocation
Dynamic Memory Allocation
Memory Allocation Functions
Releasing Memory (free)
70
Memory Allocation
71
MEMORY ALLOCATION METHODS
72
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
Ptr=(cast_type*)calloc(n,size);
79
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