unit 9 pointers with dynamic memory allocation
unit 9 pointers with dynamic memory allocation
Pointers
Introduction
Pointers are one of the powerful and a frequently used feature of C. Pointer is a variable that
contain the memory address of another variable. Variables contain the values and pointer variables
contain the address of variables that has the value. Variable directly references the value and
Pointer variable indirectly references the value. The pointer is a variable which points to the
another normal variable or another pointer is called pointer. Referencing a value through a
pointer is called indirection. The pointer has the following advantages.
The pointer enables us to access a variable that is defined outside the function.
The pointer is more efficient in handling the data tables.
It reduces the length and complexity of a program.
It allows passing variables arrays, functions, strings and structures as function arguments.
A pointer allows returning structures variables from functions.
It provides functions, which can modify their calling arguments.
It supports dynamic allocations and de-allocations of memory segments
Pointer can return more than one value.
A pointer improves the efficiency of certain routines.
Declaration
Syntax: data-type *pointer_variable_name;
Pointer operator
C provides two operators, & and *, for pointer implementation, which are inverse of each other.
& (Ampersand) operator * (Asterisk) operator
Address of operator. It is a unary Value at address or Indirection or de-
operator that returns the address of its referencing operator. It returns the value
operand. of the variable to which its operand
Synatax: data_type points.
*pointer_variable_name; Syntax: pointer_variable =
&general_variable
For example: int *myptr; For example: mypter=&x;
Initialization
Pointer variables should be initialized to 0, Null or an address. No other constant can be initialized
to a pointer variable. Pointer variable of a particular data type can, hold only the address of the
variable of same data type. For example:
Valid Invalid
int a , b , *p = &a , *q = NULL; b = &a; //Ordinary variables cannot hold address.
q = p; // Both p and q is pointing to the q = a; //cannot assign value to the pointer
memory location of variable a variable.
For example:
#include <stdio.h> ptr
#include <conio.h>
void main() 10 2293572
{ 2293568
int x=10; 2293572
int *ptr;
ptr=&x;
printf("\n Address of x = %u", &x);
printf("\n Address of x =%u",ptr);
printf("\n Address of ptr = %u", &ptr);
printf("\n Value of x = %d", x);
printf("\n Value of x = %d", *ptr);
printf("\n Value of ptr = %d", ptr);
getch(); Output:
}
Note:
Representation Description
int *p The pointer variable p is integer type pointer. In other word, p is capable to
hold the value of integer type variable.
int *p[10] p as an array of 10 pointers
int (*p)[10] p as a pointer to a set of one dimensional array of 10 elements.
int (*p) (void) p is a function that return a pointer to an integer quality.
int *p (char *a) p is a function that accept an argument which is a pointer to a character and
return a pointer to an integer quality.
Pointer assignment
A pointer is a variable data type and hence the general rule to assign its value to the pointer is same
as that of any other variable data type. For example:
int x, y;
int *ptr1,*ptr2;
Operation Description
ptr1=&x; The memory address of variables x is assigned to the pointer variable ptr1.
y=*ptr1; The contents of the pointer variables is assigned to the variable y (i.e. value of
x), not the memory address (i.e. y = ptr1 is impossible)
ptr2=ptr1; Address if ptr1 is assigned to the ptr2. The contents of both ptr1 and ptr2 will
be same as these two pointer variables hold the same address
Examples:
WAP to assign a character variable to the pointer and to display the contents of the
pointer.
#include<stdio.h>
#include <conio.h> Output:
void main() Value of x = c
{ Pointer value ptr = c
char x,y;
char *ptr;
x='c'; /*assignment of character*/
ptr=&x;
y=*ptr;
printf("Value of x = %c",x);
printf("\nPointer value ptr = %c",y);
getch();
}
Example-1:
#include <stdio.h>
#include <conio.h> Output:
void main()
{
int i=3;
printf("Address of i=%d",&i);
printf("\nValue of i = %d",i);
printf("\nValue of i using *(&i)=%d",*(&i));
getch();
}
Example-2:
#include <stdio.h>
#include <conio.h>
void main()
{
int *j,k=5;
j=&k;
clrscr(); Output:
printf("Address of k=%d",&k);
printf("\nAddress of k=%d",j);
printf("\nAddress of j=%d",&j);
printf("\nValue of j=%d",j);
printf("\nValue of k=%d",k);
printf("\nValue of k=%d",*(&k));
printf("\nValue of k=%d",*j);
getch();
}
Pointer Arithmetic
As a pointer holds the memory address of variable, some arithmetic operations can be performed
with pointers. C and C++ support four arithmetic operators that can be used with pointers, such as:
Pointer arithmetic Operator Symbol
Addition +
Subtraction -
Increment ++
Decrement --
Pointer is variables that hold that memory address of another variable. They are not integers, but
they can be displays as unsigned integers. According to data type declared to that pointer variable
if arithmetic operation is done then values (contents) will be incremented or decremented as per
the data type is chosen.
Let p = &a[0] = 1001 i.e. Base address of an array
int type pointer float type pointer char type pointer
(2-byte space) (4-byte space) (1-byte space)
p++ = p+1 = 1001 + 2 = 1003 p++ = 1001 + 4 = 1005 i.e. p++ = 1001 + 1 = 1002 i.e.
i.e. Address of next element Address of next element Address of next element
p = p+5 = 1001 + 10 = 1011 p = p+5 = 1001 + 20 = 1021 p = p+5 = 1001 + 5 = 1006 i.e.
th th
i.e. Address of 5 integer type i.e. Address of 5 float type Address of 5th char type
element. element. element.
Note: Same operation is done for decrement.
Examples:
#include
<stdio.h>
#include
<conio.h>
int main()
{
float value,*ptr;
value=120.0;
ptr=&value;
printf("\nMemory address=%u",ptr);
printf("\nvalue of this memory location
=%f\n\n\n",*ptr);
ptr++;
printf("\nMemory address after increment=%u",ptr);
ptr--;
printf("\nMemory adderss after
decrement=%u\n\n\n",ptr);
ptr=ptr+6;
printf("\nMemory adderss after
decrement=%u\n\n\n",ptr);
printf("\nvalue of this memory location[garbage]
t=%f\n\n\n",*ptr);
getch();
}
Example-2:
#include <stdio.h> Output:
#include <conio.h> Value of x=10 and pointer=10
int main() Value of y=11 and pointer=11
{
int x,y,*ptr;
x=10;
ptr=&x;
printf("Value of x=%d and pointer=%d",x,*ptr);
y=++ *ptr; /*y=11*/
printf("\nValue of y=%d and pointer=%d",y,*ptr);
getch();
}
Example-3:
#include <stdio.h>
#include <conio.h>
int main()
{
int x,y,*x_pointer,temp;
temp=3;
x=5*(temp+5); Output:
x_pointer=&temp; x =40
y=6*(*x_pointer+5); y = 48
printf("x=%d",x);
printf("\ny=%d",y);
getch();
}
Output: Output:
Values before swap Values before swap
x=100 y=20 x=100 y=20
Values after swap Values after swap
x=20 y=100 x=20 y=100
In CALL BY VALUE method, the called In CALL BY REFERENCE method, the
function creates its own copies of the called function accesses and works with the
original values sent to it. Any changes, that original values using their references. Any
are made, occur on the called function's copy changes, that occur, take place on the original
of values and are not reflected back to the values and are reflected back to the calling
calling function. code.
Example-2:
int a[5] = {1,2,3, 4,5} , *ptr , i ;
ptr = a ; // similar to ptr = &a[0];
Accessing value Accessing address
printf (“%d “,*(ptr+i)); // displays the a[i] value printf (“%u “, (ptr+i)); // displays address
printf (“%d “,*ptr); //displays the a[0] value of a(i)
printf (“%d “,*(a+i)); // displays the a[i] value
For example-2: A program to access the array element and particular memory location using
pointer.
Using pointer
#include <stdio.h>
#include <conio.h>
int main()
{ int x[]={10,20,30,40,50};
int i, *p;
p = &x[0];
for(i=0;i<5;i++)
{
printf("\nArray element = %d\t and Memory location = %u", *p, p);
p = p+1;
}
getch();
}
Array of pointer (Pointer variables)
As in above program, we cannot increment the pointer constant but the pointer variable can be
incremented as shown in following figure. While we can’t increment an address, we can increment
a pointer that holds an address.
For example-1:
#include <stdio.h>
#include <conio.h>
void main()
{
int myArray[]={1,2,3,4,5};
int *ptr2myArray,i;
clrscr();
ptr2myArray=myArray;
for(i=0;i<5;i++)
printf("%d\t",*(ptr2myArray++));
getch();
}
Output: 1 2 3 4 5
For example-2:
#include <stdio.h>
#include <conio.h>
int main()
{
int *A[3];
int x, y, z,i;
x=2;
y=5;
z=6;
A[0] = &x;
A[1] = &y;
A[2] = &z;
for( i=0;i<=2;i++)
{
printf("\n %u address \t and value is %d",A[i],*A[i]);
getch();getch();
}
Output:
Passing arrays using pointers
As we passed the variables onto the function based using pointer in the same way arrays are passed
as arguments to functions and their elements being access by the function. However, it’s more
common to use pointer notation instead of array notation when arrays are passed to the function.
For example:
#include
<stdio.h>
#include
<conio.h>
#define MAX 5
void multiply_array(int *myArray);
int main()
{
int myArray[MAX]={10,12,14,16,18},j;
multiply_array(myArray);
for(j=0;j<MAX;j++)
printf("myArray[%d]:%d\n",j,myArray[j]);
getch();
}
For example:
#include <stdio.h>
#include <conio.h>
#include <alloc.h>
void output(char *s);
int main()
{
char s[20];
printf("Enter a word:");
scanf("%s",s);
printf("\nOutput:");
output(s);
getch();
}
For example:
#include <stdio.h>
#include <conio.h>
int main()
{
char str1[]="This is a string stored in an array";
char *str2="This is string stored using pointer";
printf("%s",str1);
printf("\n%s",str2);
getch();
}
Output:
This is a string stored in an array
This is string stored using pointer
WAP to copy string form one array to another array.
#include <stdio.h>
#include <conio.h>
#include <alloc.h>
void output(char *s,char *d);
int main()
{
char s[20],d[20];
printf("Enter a word:");
scanf("%s",s);
output(s,d);
printf("\nOutput: %s",d);
getch();
}
void output(char *s,char *d)
{
while((*s)!='\0')
*d++ = *s++;
*d='\0';
}
#include<stdio.h>
#include<conio.h>
main()
{
char *s[10];
int i;
printf("enter names");
for(i=0;i<3;i++)
scanf("%s",&s[i]);
printf("\n name are");
for(i=0;i<3;i++)
printf("\n\t %s",s[i]);
getch();
}
strcat(str, "college");
free(str);
getch();
}
Write a program to input N numbers into a dynamic array and sort them in ascending order.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
main()
{
int *num;
int i,j,n,temp;
printf("\n enter the value of n");
scanf("%d",&n);
num = (int *) malloc(n);
printf("\n enter %d numbers",n);
for(i=0;i<n;i++)
scanf("%d",&num[i]);
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(num[i]>num[j])
{
temp=num[i];
num[i]=num[j];
num[j]=temp;
}}}
printf("\n sorted numbers are ");
for(i=0;i<n;i++)
printf(" %d",num[i]);
getch();
}
printf("Second value: %f\n", (*ptr_one).PI);
printf("Third value: %c\n", (*ptr_one).A);
free(ptr_one);
getch();
Output:
return 0;
First value: 10
} Second value: 3.140000
Third value: a
B. Function: calloc()
The C library function allocates the requested memory and returns a pointer to it.
Syntax:
void *calloc (number_of_blocks, size_of_each_block_in_bytes);
This function returns a pointer to the allocated memory, or NULL if the request fails.
For example: a = calloc (n, sizeof (int)); This allocates contiguous space in
memory for an array of n-elements with each element having 2-byte memory (since for int).
Here ‘a’ is an array variable.
Output:
Enter the number of type int to allocate: 100
Memory allocation was successful.
Enter the number of type int to allocate: 99999999
Memory allocation failed.
malloc () calloc ()
1. The term malloc stands for memory 1. The term calloc stands for contiguous
allocation. allocation.
2. The malloc is dynamic memory allocation 2. The calloc is similar to malloc but only
it allocates the memory and initializes difference is initialize zero
garbage value.
3. malloc create the memory space 3. calloc calculate the memory space
4. malloc take one argument i.e. 4. calloc take two argument i.e.
(malloc(sizeof(int)*10) and allocate bytes (calloc(no.of.var, size of each var) and
of memory. allocate block of memory.
5. malloc allocates memory as a single 5. calloc allocates memory which may/may
contiguous block. not be contiguous.
6. if a single contiguous block cannot be 6. it follows from point 2 that calloc will not
allocated then malloc would fail. fail if memory can be allocated in non-
contiguous blocks when a single
7. No need to free the memory explicitly contiguous block cannot be allocated
while using malloc. Variables used with 7. But one needs to free the memory
malloc are destroyed automatically explicitly while variables are created using
calloc
8. malloc allocates memory requests size of 8. malloc allocates memory requests size of
bytes and returns a pointer to the 1st byte of bytes and returns a pointer to the 1st byte
allocated space of allocated space
16
The c library function void realloc() attempts to resize the memory block pointed to by ptr that was
previously allocated with a call to malloc() or calloc() function.
The c library function void free() deallocates the memory previously created by malloc() or realloc() or
calloc() functions.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char *ptr;
int n;
printf("enter the size of memroy");
scanf("%d",&n);
ptr=(char *) malloc(n);
strcpy(ptr,"lict");
printf("enter again the size of memroy");
scanf("%d",&n);
ptr=(char *) realloc(ptr,n);
strcat(ptr,".edu.np");
printf("\n entire string is %s",ptr);
free(ptr);
getch();
}