0% found this document useful (0 votes)
20 views17 pages

Unit 4

unit4 ppsc

Uploaded by

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

Unit 4

unit4 ppsc

Uploaded by

mounica
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT-4

POINTERS

INTRODUCTION:

POINTER:

A pointer is used to store the address of variable .

Declaration of pointer variable:

Syntax:

datatype *pointervariable;

Ex:

int *i;//integer pointer variable ‘i’ which stores address of integer variable.

float *b;// floating pointer variable ‘b’ which stores address of floating point variable.

char *ch;// character pointer variable ‘ch’ which stores address of character variable.

Initialization of pointer variable:

Syntax:

datatype *pointername;

pointername=&variablename;

Ex:

int *a,b=10; a b
2002 10
a=&b;

2000 2002

• In pointers we use 2 operators:


I.&-known as addressof operator or referencing operator-it is used to store address of
variable.
ii.*-known as dereferencing or valueat address of operator.

Example program for pointers:

#include<stdio.h>

#include<conio.h>
main()

{ a ptr

int a=10,*ptr; 10 1000

ptr=&a; 1000 1002

printf(“value of a is %d\n”,a);

printf(“value of a is %d\n”,*ptr);

printf(“value of a is %d\n”,*(&a));

printf(“value of a is %d\n”,*(*(&ptr)));

printf(“address of a is %u\n”,ptr);

printf(“address of a is %u\n”,&a);

printf(“address of ptr is %u\n”,&ptr);

getch();

Output:

value of a is 10

value of a is 10

value of a is 10

value of a is 10

address of a is 1000

address of a is 1000

address of ptr is 1002

Types of pointers:
1. NULL POINTER:

• A null pointer is a special pointer that doesn’t point to any value. This means that a
null pointer doesn’t point to any valid memory address.
• To declare a null pointer, you may use the predefined constant NULL,which is defined
in several standard header files including <stdio.h>,<stdlib.h> and <string.h>
Ex: int *ptr=NULL;
• We can check whether a given pointer variable stores address of some variable or
contains a NULL string by writing
If(ptr==NULL)
{
Statement block;
}
• We may also initialize a pointer as a NULL pointer by using a constant 0,as shown
below:
int ptr;
ptr=0;
• Null pointers are used in situations where one of the pointers in the program points to
different locations at different times.
• In such situations ,it is always better to set it to a NULL pointer when it doesn’t point
anywhere valid, and to test to see if it’s a null pointer before using it.

2. GENERIC POINTER:

• A generic pointer is a pointer that has void as datatype.


• The void pointer or generic pointer is a special type of pointer that can be used to point
to variables of any data type.
• It is declared like a normal pointer variable but using the void keyword as the pointers
datatype.
Ex: void *ptr;
• In C,since you cannot have a variable of type void,the void pointer will therefore not
point to any data and thus cannot be dereferenced.
• You need to typecast a void pointer (Generic pointer) to another kind of pointer before
using it.
• Generic pointers are often used when you want a pointer to point to different datatypes
at different times.

Example program:

#include<stdio.h>

#include<conio.h>

main()

int x=10;

char ch=’a’;

float f=1.23;

void *gp;

gp=&x;
printf(“generic pointer points to the integer value=%d”,*(int *)gp);

gp=&ch;

printf(“generic pointer points to the character value=%c”,*(char *)gp);

gp=&f;

printf(“generic pointer points to the character value=%f”,*(float *)gp);

getch();

Output:

generic pointer points to the integer value=10

generic pointer points to the character value=a

generic pointer points to the character value=1.230000

POINTER TO POINTER:

• In this, by using one pointer, we will store the address of another pointer i.e.,
pointer stores the address of another pointer.

Declaring pointer to pointer:

Syntax:

datatype **pointervariable;

Example program for pointer to pointers:

#include<stdio.h>

#include<conio.h>

main()

{ a ptr1 ptr2 ptr3


10 1000 1002 1004
int a=10;

int *ptr1,**ptr2,***ptr3; 1000 1002 1004 1006

ptr1=&a;

ptr2=&ptr1;

ptr3=&ptr2;
printf(“the value of a is %d\n”,a);

printf(“the value of ptr1 is %d\n”,*ptr1);

Printf(“the value of ptr2 is %u\n”,*ptr2);

Printf(“the value of ptr3 is %u\n”,*ptr3);

getch();

Output:

the value of a is 10

the value of ptr1 is 10

the value of ptr2 is 1000

the value of ptr3 is 1002

COMPATABILITY:

• You can assign an integer value to a double variable without using type conversion
in numeric types, but we cannot do the same to the pointers.
Example program:
#include<stdio.h>
#include<conio.h>
main()
{
int a=10;
double d=20.1234567;
int *ptr1,*ptr2;
ptr1=&a;
ptr2=&d;//error because ptr2 is integer pointer and ‘d’ is double value
printf(“the value of ptr1 is %u\n”,ptr1);
printf(“the value of ptr2 is %u\n”,ptr2);
getch();
}

L-VALUE AND R-VALUE :

• “l-value” refers to memory location which identifies an object. l-value may appear as
either left hand or right hand side of an assignment operator(=).
• l-value often represents as identifier.
• The name of the identifier denotes a storage location.
Operators that require L-value expression:
TYPE OF EXPRESSION EXAMPLES
Address operator &score
Postfix increment/decrement X++,y--
Prefix increment/decrement ++x,--y
Assignment(left operand) X=1,y+=3(y=y+3)

• “r-value” refers to data value that is stored at some address in memory.


• r-value can appear on right but not on left hand side of an assignment operator(=).
Invalid r-value Expressions:

EXPRESSION PROBLEM
A+2=6; A+2 is an r-value and cannot be the left
operand in an assignment. It is a
temporary value that doesn’t have an
address;no place to store 6
&(a+2) (a+2) is an r-valu,and the address
operator needs l-value.
&4; Same as above(4 is an r-value).

(a+2)++; Postfix and prefix operators require l-


++(a+2); values;(a+2) is an r-value.

II POINTER APPLICATIONS

POINTER TO ARRAYS:

• In pointer to array, the pointer stores address of the array. suppose we declare an
array x as follows:
int x[5]={6,0,2,5,1};
Then the elements will be stored as

Element-→ x[0] x[1] x[2] x[3] x[4]

Value→ 6 0 2 5 1

Address→ 2000 2002 2004 2006 2008

• Now if an integer pointer *ptr is declared and the address of 1st element is stored in
ptr,then
int *ptr;
ptr=&x[0];

Then,

ptr=&x[0]=2000;

ptr+1=&x[1]=2002;

ptr+2=&x[2]=2004;

ptr+3=&x[3]=2006;

ptr+4=&x[4]=2008;
so,

*(ptr+2)=x[2]=2;

Program to explain the concept of pointers in 1D array:

#include<stdio.h>

#include<conio.h>

main()

int x[5]={6,0,2,5,1};

int *ptr,i;

ptr=&x[0];//assigning base address to pointer

printf(“elements in array are:\n”);

for(i=0;i<5;i++)

printf(“%d stored at address %u”,*ptr,ptr);

ptr++;

getch();

Output:

Elements In array are:

6 stored at address 2000

0 stored at address 2002

2 stored at address 2004

5 stored at address 2006

1 stored at address 2008

POINTER AND 2D ARRAYS:

• Consider a 2D array ‘a’ with size of 2*2


int a[2][2]={{2,1},{3,4}};
• Then, the memory representation is as follows:

Row1 Row2

Values-→ 2 1 3 4
Index→
a[0][0] a[0][1] a[1][0] a[1][1]
Memory location 2000 2002 2004 2006
• Now if the base address of the array i.e., &a[0][0] is assigned to pointer ‘ptr’,then the 2D
array can be traversed by incrementing ‘ptr’ i.e.,
int *ptr;
ptr=&a[0][0];
ptr+1=&a[0][1];
ptr+2=&a[1][0];
ptr+3=&a[1][1];
Then *(&(a[0][1]))=1
Program to explain the concept of pointers and 2D arrays:
#include<stdio.h>
#include<conio.h>
main()
{
int a[2][2]={{2,1},{3,4}};
int *ptr,i,j;
printf(“elements of 2d array are:\n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(“%d\t”,*ptr);
ptr++;
}
printf(“\n”);
}
}
POINTER ARITHMETIC:
The arithmetic operations that we can perform on pointers are:
1. Incrementation of pointers
2. Decrementation of pointers
3. Adding a number to pointer
4. Subtracting a number from pointer
5. Subtracting two pointer variables

Invalid pointer arithmetic operators are:


1. Addition of two pointer variables
2. Multiplication of two pointer variables
3. Division of two pointer variables
4. Modulo operation of two pointer variables

Program to demonstrate pointer arithmetic:

#include<stdio.h>

#include<conio.h>

main()

int *ptr1,*ptr2;

int a[5]={10,20,30,40,50};

ptr1=&a[0];

printf(“initially the ptr1 value is %u\n”,ptr1);

ptr1++;

printf(“after incrementing the ptr1 value is %u\n”,ptr1);

ptr2=&a[4];

printf(“initially the ptr2 value is %u\n”,ptr2);

ptr2--;

printf(“after decrementing the ptr2 value is %u\n”,ptr2);

ptr1=ptr1+2;

printf(“the ptr1 value is %u\n”,ptr1);

ptr2=ptr2-2;

printf(“the ptr2 value is %u\n”,ptr2);

getch();

ARRAY OF POINTERS:

Array of pointers stores the collection of addresses.

Syntax:

datatype *arrayname[size];
Ex: int *a[10];//by using this, we can store 10 addresses of integer values.

float *c[5];//by using this, we can store 5 addresses of floating point values.

char *d[5];//by using this,we can store 5 addresses of character values.

Program to demonstrate array of pointers:

#include<stdio.h>

#include<conio.h>

main()

int a=10,b=20,c=30; a 10 b 20 c 30

int *ptr[10]; 1000 2002 3032

clrscr(); ptr

ptr[0]=&a;

ptr[1]=&b; ptr[0] ptr[1] ptr[2] ptr[3] ptr[4] ptr[5] ptr[6] ptr[7] ptr[8] ptr[9]

ptr[2]=&c; 4000 4002 4004 4006 4008 4010 4012 4014 4016 4018

printf(“the address of a is %u\n”,ptr[0]);

printf(“the value of a is %d\n”,*ptr[0]);

printf(“the address of b is %u\n”,ptr[1]);

printf(“the value of b is %d\n”,*ptr[1]);

printf(“the address of c is %u\n”,ptr[2]);

printf(“the value of c is %d\n”,*ptr[2]);

getch();

MEMORY ALLOCATION:

There are 2 ways to allocate memory to the variables.

1. Static memory allocation


2. Dynamic memory allocation

Static memory allocation:

In this memory allocation,the memory is allocated at compile time.


Disadvantages:

[Link] use static memory allocation.

Ex: int a[5];we can store 5 elements

[Link] memory is allocated, it is not possible to change the size of the array.

[Link] more memory is allocated than required, the memory is wasted.

Ex: int a[100];if we the memory to store 5 elements then remaining memory is wasted.

[Link] less memory is allocated than the required, we can’t store more elements.

Ex: int a[5];cant store more than 5 elements.

Dynamic memory allocation:

• To overcome the limitations of static memory allocation, dynamic memory allocation is


used.
• The memory which is allocated during execution/runtime.
• To implement dynamic memory allocation, we have 4 functions:
1. Malloc
2. Calloc
3. Realloc
4. Free

Memory allocation(malloc):

• Malloc is mainly used to allocate memory to a pointer variable during execution time.
• It allocates requested size in terms of bytes and returns pointer to the starting address
of the memory block.
• Malloc allocates only one block of memory.
Syntax:
datatype *pointervariable=(datatype *)malloc(type size);
Ex: int *ptr=(int *)malloc(n*sizeof(2));
If the number of elements are 5 then 10 bytes of memory is allocated for pointer
variable ptr.
• Malloc function accepts only one argument i.e., byte size.
• The default initial values are garbage values.

C program to demonstrate malloc function:

#include<stdio.h>

#include<string.h>

main()
{

int i,n;

int *ptr;

printf("enter the size of array\n");

scanf("%d",&n);

ptr=(int *)malloc(n*sizeof(int));

printf("enter the elements of array\n");

for(i=0;i<n;i++)

scanf("%d",&ptr[i]);

printf("the values of array are\n");

for(i=0;i<n;i++)

printf("%d\t",ptr[i]);

Output:

enter the size of array

enter the elements of array

10 20 30 40 50

the values of array are

10 20 30 40 50

Example program:(Allocating Memory for structures using Malloc )

#include<stdio.h>

#include<stdlib.h>
main()

struct student

int rno;

float per;

};

struct student *ptr;

ptr=(struct student*)malloc(sizeof(struct student));

if(ptr==NULL)

printf("memory not allocated\n");

else

printf("enter the student details\n");

printf("enter the roll number\n");

scanf("%d",&ptr->rno);

printf("enter the percentage\n");

scanf("%f",&ptr->per);

printf("roll number of student is %d\n",ptr->rno);

printf("percentage of student is %f\n",ptr->per);

Output:

enter the student details

enter the roll number


10

enter the percentage

98

roll number of student is 10

percentage of student is 98

CONTIGUOUS ALLOCATION(CALLOC):

• calloc is useful to allocate memory to a pointer variable during execution time.


• It allocates multiple blocks of memory and returns pointer to the starting block/first
block.
Syntax:
Datatype *pointer=(datatype *)calloc(number of blocks,size of block);
Ex: int *ptr=(int *)calloc(5,2);
• calloc function requires 2 arguments
• Default initial values are zero.

C program to demonstrate calloc function:

#include<stdio.h>

main()

int i,n;

int *ptr;

printf("enter the size of array\n");

scanf("%d",&n);

ptr=(int *)calloc(n,sizeof(int));

printf("eneter the eleemnts of array\n");

for(i=0;i<n;i++)

scanf("%d",&ptr[i]);
}

printf("the values of array are\n");

for(i=0;i<n;i++)

printf("%d\t",ptr[i]);

Output:

enter the size of array

enter the elements of array

10 20 30 40 50

the values of array are

10 20 30 40 50

REALLOC FUNCTION:

• It is used to modify the size of the allocated memory.


Syntax:

realloc(pointervariable,bytesize);

C program to demonstrate realloc function:

#include<stdio.h>

#include<stdlib.h>

main()

char *str;

str=(char *)malloc(5);
if(str==NULL)

printf("Memory not allocated\n");

strcpy(str,"hell");

printf("the string is %s\n",str);

str=(char *)realloc(str,20);

if(str==NULL)

printf("Memory not allocated\n");

strcpy(str,"hello world ");

printf("the string is %s\n",str);

Output:

The string is hell

The string is hello world

Free:

• Free function frees the memory allocated by malloc and calloc functions.

You might also like