You are on page 1of 20

4/13/2022

Pointer int main ()


{
int var1=10;
printf("Address of var1: %x\n", &var1 );
printf("Address of var1: %u\n", &var1 );
printf(“Value of var1: %d\n", var1 );
return 0;
}
Output:
Address of var1: fff4
Address of var1: 65535
Value of var1: 10

Benefit of using pointers


Pointers are more efficient in handling Array and
Structure.
Pointer allows references to function and thereby
helps in passing of function as arguments to
other function.
It reduces length and the program execution time.
It allows C to support dynamic memory management.

How to use Pointers? Pointer Operator


(a) we declare a pointer variable
(b) assign the address of a variable to a pointer Operator Operator Name Purpose
and
* Value at Gives Value stored at
(c) finally access the value at the address Operator Particular address
available in the pointer variable.
This is done by using unary operator * that & Address Gives Address of
returns the value of the variable located at the Operator Variable
address specified by its operand.

1
4/13/2022

Initialization of Pointer
Declaring a pointer variable
variable
data-type *pointer_name; Pointer Initialization is the process of
Data type of pointer must be same as the assigning address of a variable
variable, which the pointer is pointing. to pointer variable.
void type pointer works with all data types, but Pointer variable contains address of variable of
isn't used oftenly. same data type.
In C language address operator & is used to
determine the address of a variable.
The & (immediately preceding a variable name)
returns the address of the variable associated
with it.
int a = 10 ;
int *ptr ; //pointer declaration
ptr = &a ; //pointer initialization or,
int *ptr = &a ; //initialization and declaration
together

Dereferencing of Pointer
Pointer variable always points to same type of Once a pointer has been assigned the address of a
data. variable. To access the value of variable,
float a; pointer is dereferenced, using the indirection
operator *.
int *ptr;
int a,*p;
ptr = &a; //ERROR, type mismatch
a = 10;
p = &a;
printf(“%d”, *a); // ERROR, invalid indirection
printf("%d",*&a); //this will also print the
value of a. printf(“%x", &a); //this will print
the address of a.
printf("%x", p); //this will also print the
address of a.
printf("%d",*p); //this will print the value of
a.

int main () Output:


{ Address of var variable: bffd8b3c
int var = 20; Address stored in ip variable: bffd8b3c
int *ip; Value of *ip variable: 20
ip = &var;
printf("Address of var variable: %x\n", &var );
printf("Address stored in ip variable: %x\n", ip
);
printf("Value of *ip variable: %d\n", *ip );
return 0;
}

2
4/13/2022

NULL Pointers
It is always a good practice to assign a NULL int main ()
value to a pointer variable in case you do not {
have exact address to be assigned.
int *ptr = NULL;
This is done at the time of variable declaration.
printf("The value of ptr is : %x\n", ptr );
A pointer that is assigned NULL is called
return 0;
a null pointer.
}

Output:
The value of ptr is 0

Void Pointers
On most of the operating systems, programs are Suppose we have to declare integer pointer,
not permitted to access memory at address 0 character pointer and float pointer then we need
because that memory is reserved by the operating to declare 3 pointer variables.
system. However, the memory address 0 has special Instead of declaring different types of pointer
significance; it signals that the pointer is not variable it is feasible to declare single pointer
intended to point to an accessible memory variable which can act as integer pointer,
location. But by convention, if a pointer character pointer.
contains the null (zero) value, it is assumed to
point to nothing.
if(ptr) /* succeeds if p is not null */
if(!ptr) /* succeeds if p is null */

Void Pointer Basics


In C General Purpose Pointer is called as void Declaration of Void Pointer :
Pointer. void * pointer_name;
It does not have any data type associated with it
It can store address of any type of variable
A void pointer is a C convention for a raw
address.
The compiler has no idea what type of object a
void Pointer really points to ?

3
4/13/2022

Void Pointer Example


void *ptr; // ptr is declared as Void pointer Scenario Behavior
char cnum; When We assign address of Void Pointer Becomes
int inum; integer variable to void Integer Pointer
float fnum; pointer
ptr = &cnum; // ptr has address of character data When We assign address of Void Pointer Becomes
ptr = &inum; // ptr has address of integer data character variable to Character Pointer
ptr = &fnum; // ptr has address of float data void pointer
When We assign address of Void Pointer Becomes
floating variable to void Floating Pointer
pointer

Key points to remember about


pointers
Normal variable stores the value whereas pointer But, Pointer addition, multiplication, division
variable stores the address of the variable. are not allowed.
The content of the C pointer always be a whole The size of any pointer is 2 byte (for 16 bit
number i.e. address. compiler).
Always C pointer is initialized to null, i.e. int
*p = null.
The value of null pointer is 0.
& symbol is used to get the address of the
variable.
* symbol is used to get the value of the variable
that the pointer is pointing to.
If pointer is assigned to NULL, it means it is
pointing to nothing.
Two pointers can be subtracted to know how many
elements are available between these two

Pointer Arithmetic Incrementing Pointer


Incrementing Pointer let us consider that ptr is an integer pointer
which points to the address 1000.
Decrementing Pointer
Assuming 32-bit integers, let us perform the
Addition of Pointer and Number following arithmetic operation on the pointer:
Subtraction of Pointer and Number ptr++
Differencing between two pointers Now, after the above operation, the ptr will
Comparing two Popinters point to the location 1004 because each time ptr
is incremented, it will point to the next integer
location which is 4 bytes next to the current
location. This operation will move the pointer to
next memory location without impacting actual
value at the memory location.
If ptr points to a character whose address is
1000, then above operation will point to the
location 1001 because next character will be
available at 1001.

4
4/13/2022

const int MAX = 3;


int main ()
We prefer using a pointer in our program instead
{
of an array because the variable pointer can be
incremented, unlike the array name which cannot int var[ ] = {10, 100, 200};
be incremented because it is a constant pointer. int i,*ptr;
The following program increments the variable ptr = var;
pointer to access each succeeding element of the for ( i = 0; i < MAX; i++)
array: {
printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
ptr++;
}
return 0;
}

Decrementing a Pointer
Output: const int MAX = 3;
Address of var[0] = bf882b30 int main ()
Value of var[0] = 10 {
Address of var[1] = bf882b34 int var[] = {10, 100, 200};
Value of var[1] = 100 int i, *ptr;
Address of var[2] = bf882b38 ptr = &var[MAX-1];
Value of var[2] = 200 for ( i = MAX; i > 0; i--)
{
printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
ptr--;
}
return 0; }

Addition of Pointer and Number


Address of var[3] = bfedbcd8 We can add any integer number to Pointer
Value of var[3] = 200 variable.
Address of var[2] = bfedbcd4 It is perfectly legal in c programming to add
integer to pointer variable.
Value of var[2] = 100
In order to compute the final value we need to
Address of var[1] = bfedbcd0
use following formula:
Value of var[1] = 10
final value = (address) + (number * size of data
type)
Consider the following example –
int *ptr , n;
ptr = &n ;
ptr = ptr + 3;

5
4/13/2022

Subtraction of Pointer and


Number
int main() new_address = (current_ address) - i *
{ size_of(data type)
int *ptr=(int *)1000; Decrementation of Pointer Variable Depends Upon :
data type of the Pointer variable
ptr=ptr+3;
int main()
printf("New Value of ptr : %u",ptr);
{
return 0;
int *ptr=(int *)1000;
}
ptr=ptr-1;
Output :
printf("New Value of ptr : %u",ptr);
New Value of ptr : 1006
return 0;
}
Output :
New Value of ptr : 998

Differencing between two


pointers
Differencing Means Subtracting two Pointers. #include<stdio.h>
Subtraction gives the Total number of objects int main()
between them. {
Subtraction indicates “How apart the two Pointers int num , *ptr1 ,*ptr2 ;
are ?”
ptr1 = &num ;
ptr2 = ptr1 + 2 ;
printf("%d",ptr2 - ptr1);
return 0;
}
Output : 2
ptr1 stores the address of Variable num
Value of ptr2 is incremented by 4 bytes

#include<stdio.h> Explanation :
int main() Ptr1 and Ptr2 are two pointers which holds memory
{ address of Float Variable.
float *ptr1=(float *)1000; Ptr2-Ptr1 will gives us number of floating point
numbers that can be stored.
float *ptr2=(float *)2000;
ptr2 - ptr1 = (2000 - 1000) / sizeof(float) =
printf("\nDifference : %d",ptr2-ptr1);
1000 / 4 = 250
return 0;
}
Output :
Difference : 250

6
4/13/2022

Pointer Comparisons
Expression Result Pointers may be compared by using relational
operators, such as ==, <, and >.
Address + Number Address
If p1 and p2 point to variables that are related
Address – Number Address to each other, such as elements of the same
array, then p1 and p2 can be meaningfully
Address – Address Number
compared.
Address + Address Illegal The following program modifies the previous
example one by incrementing the variable pointer
so long as the address to which it points is
either less than or equal to the address of the
last element of the array, which is &var[MAX -
1]:

const int MAX = 3;


int main ()
{ Address of var[0] = bfdbcb20
int var[] = {10, 100, 200}; Value of var[0] = 10
int i, *ptr; Address of var[1] = bfdbcb24
ptr = var; Value of var[1] = 100
i = 0; Address of var[2] = bfdbcb28
while ( ptr <= &var[MAX - 1] ) Value of var[2] = 200
{
printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
ptr++;
i++;
}
return 0; }

Array of Pointers const int MAX = 3;


int main ()
There may be a situation when we want to maintain {
an array, which can store pointers to an int or
int var[] = {10, 100, 200};
char or any other data type available.
int i, *ptr[MAX];
Following is the declaration of an array of
pointers to an integer: for ( i = 0; i < MAX; i++)
int *ptr[MAX]; {
This declares ptr as an array of MAX integer ptr[i] = &var[i];
pointers. Thus, each element in ptr, now holds a }
pointer to an int value. for ( i = 0; i < MAX; i++)
{
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
return 0;
}

7
4/13/2022

Pointer to Pointer
Value of var[0] = 10 A pointer to a pointer is a form of multiple
Value of var[1] = 100 indirection, or a chain of pointers.
Value of var[2] = 200 Normally, a pointer contains the address of a
variable.
When we define a pointer to a pointer, the first
pointer contains the address of the second
pointer, which points to the location that
contains the actual value as shown below.

When a target value is indirectly pointed to by a


pointer to a pointer, accessing that value
requires that the asterisk operator be applied
twice, as is shown below in the example:

A variable that is a pointer to a pointer must be


declared as such.
This is done by placing an additional asterisk in
front of its name.
For example, following is the declaration to
declare a pointer to a pointer of type int:
int **var;

int main ()
{
Value of var = 3000
int var;
Value available at *ptr = 3000
int *ptr;
Value available at **pptr = 3000
int **pptr;
var = 3000;
ptr = &var;
pptr = &ptr;
printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n",
**pptr);
return 0;
}

8
4/13/2022

How much Memory required to


store Pointer variable?
void main() Pointer Variable Stores the address of the
{ variable
int a = 3; Variable may be integer, character, float but
the address of the variable is always integer so
int *ptr,**pptr;
Pointer requires 2 bytes of memory in Turbo C
ptr = &a; Compiler.
pptr = &ptr; If we run same program in any other IDE then the
} output may differ.
This requirement is different for
different Compilers.

Size of integer pointer Size of Character Pointer


void main() void main()
{ {
int a = 10, *ptr; char a = 'a', *cptr;
ptr = &a; cptr = &a;
printf("\nSize of Integer Pointer : %d“, printf("\nSize of Character Pointer :
sizeof(ptr)); %d",sizeof(cptr));
} }
Output : Output :
Size of Integer Pointer : 2 Size of Character Pointer : 2

Precedence of ‘ * ‘ and ‘ & ‘


Size of Float Pointer
Operator
void main() Both are Unary Operators
{ They have Equal Precedence
float a = 3.14, *fptr; They Associate from Right -> Left
fptr = &a;
printf("\nSize of Character Pointer : %d",
sizeof(fptr));
}
Output :
Size of Float Pointer : 2

9
4/13/2022

Meaning of (*++ptr
(*++ ptr))
Consider the Following Example : Calculation of Answer :
int n = 20 , *ptr ; * ++ptr = *(++ptr ) = *( 3060 ) = Value Stored at
ptr = &n; Location 3060
printf("%d",*++ptr); #include<stdio.h>
Explanation : int main()
‘++’ and ‘*’ both have Equal Precedence {
Associativity is from Right to Left ( Expression int n = 20 , *ptr ;
evaluated from R->L) ptr = &n;
Both are Unary (Operates on single operand ) printf("%d",*++ptr);
So ‘ ++ ‘ is Performed First then ‘ * ‘ return(0);
}
Output :
Garbage Value gets printed

How to use *++ptr


*++ptr in Array
Program ?
Note : #include<stdio.h>
This operation should not be used in normal int main()
operation. {
Perform this operation if we have consecutive int arr[5] = {10,20,30,40,50};
memory i.e Array.
int *ptr ;
If we perform this operation in above example
ptr = arr;
then we will get garbage value as we dont know
the value stored at 3060. printf("%d",*++ptr);
return 0;
}
Output :
20

Meaning of (++*ptr
(++*ptr)
) pointer Are ++*ptr
++*ptr and *ptr
*ptr++
++ are same ?
int num = 20 , *ptr ; Step by Step Explanation of : ++*ptr
ptr = &num; Address of Num : 1000
printf("%d",++*ptr); ++ *ptr =++ *(1000)
Explanation : =++ (Value at address 1000)
‘++’ and ‘*’ both are having equal precedence =++ 10 = 11
and priority. Associativity of these two Step by Step Explanation of : *ptr++
operators is from right to left (Expression
Address of Num : 1000
evaluated from R->L)
*ptr++ = *1000 ++ = Value at address 1000 ++ = 10
Both the operators are Unary so they will only
++ = 10
works on single operand
Dereference operator ‘*’ will get chance for
execution before pre increment operator ‘++’.

10
4/13/2022

Pointer to Constant Objects


Syntax : “const int” means integer is constant.
const data-type *pointer_name ; We cannot change value of the integer.
Example : Pointer to Such Object cannot be changed.
int n = 30 ; We can change address of such pointer so that it
const int *ptr; will point to new memory location.
ptr = &n; Following is illegal use of const int pointer –
*ptr = 20 ;
however we can use this legally –
ptr++ is valid in this Case !!!

How const int Pointer works ? Increment const int Pointer


#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int num[2] = {10,20}; int num[2] = {10,20};
const int *ptr; const int *ptr;
ptr = &num[0]; ptr = &num[0];
printf("%d",*ptr); ptr++;
return(0); printf("%d",*ptr);
} return(0);
Output: }
10 Output :
20

Assigning Value to const int


What is Constant Pointers?
pointer
int main() Constant Pointers Cannot be modified.
{ Modification in Integer to which it Points to is
int num[2] = {10,20}; Allowed
const int *ptr; Modification made in Pointer is Not Allowed
ptr = &num[0]; Syntax:
*ptr = 30; data type * const Pointer name = Initial Address;
printf("%d",*ptr); Example:
return(0); int num = 20;
} int * const ptr = &num ; // Declare Constant
Pointer
Output :
*ptr = 20 ; // Valid Statement
Compile Error
ptr ++ ; // Invalid Statement
Can not modify a constant object

11
4/13/2022

Passing pointers to functions


We can DO following operations on const pointer C programming language allows you to pass a
– pointer to a function. To do so, simply declare
Assigning Value at Address the function parameter as a pointer type.
Printing Address or Value Following a simple example where we pass an
Assigning Address at the time of declaration. unsigned long pointer to a function and change
the value inside the function which reflects back
We Can’t DO following operations on const in the calling function.
pointer –
Adding Integer to const Pointer
Subtracting Integer to const Pointer.
Any operation that can change address of pointer.

swapnum ( int *num1, int *num2 )


{
swapnum ( &v1, &v2 );
int tempnum ;
printf("After swapping:");
tempnum = *num1 ;
printf("Value of v1 is: %d", v1);
*num1 = *num2 ;
printf("Value of v2 is: %d", v2);
*num2 = tempnum ; }
}
int main( )
{
int v1 = 11, v2 = 77 ;
printf ("Before swapping:");
printf("Value of v1 is: %d", v1);
printf("Value of v2 is: %d", v2);

Return pointer from functions


Output: int* larger(int*, int*);
Before swapping: void main()
Value of v1 is: 11 {
Value of v2 is: 77 int a=15;
After swapping: int b=92;
Value of v1 is: 77 int *p;
Value of v2 is: 11 p=larger(&a, &b);
printf("%d is larger",*p);
}

12
4/13/2022

Returning Array from function


int* larger(int *x, int *y) We dont't return an array from functions, rather
{ we return a pointer holding the base address of
the array to be returned. But we must, make sure
if(*x > *y)
that the array exists after the function ends.
return x;
int* sum (int x[])
else
{
return y;
for(i=0;i<5;i++)
}
{
x[i]=i*10;
}
return x ;
}

Row–
Row –Major Space Allocation

Pointer to 1-
1-D Array
An array name is a constant pointer to the first Here variable arr will give the base address,
element of the array. which is a constant pointer pointing to the
When an array is declared, compiler allocates element, arr[0]. Therefore arr is containing the
sufficient amount of memory to contain all the address of arr[0] i.e 1000.
elements of the array. arr is equal to &arr[0] // by default
Suppose we declare an array arr, We can declare a pointer of type int to point to
int arr[5]={ 1, 2, 3, 4, 5 }; the array arr.
Assuming that the base address of arr is 1000 and int *p;
each integer requires two byte, the five element p = arr; // or
will be stored as follows p = &arr[0]; // both the statements are
equivalent.
Now we can access every element of
array arr using p++ to move from one element to
another.

13
4/13/2022

int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i=0; i<5; i++)
{
printf("%d", *p);
p++;
}

int main ()
{
It is legal to use array names as constant double balance[5] = {1000.0, 2.0, 3.4, 17.0,
pointers, and vice versa. Therefore, *(balance + 50.0};
4) is a legitimate way of accessing the data at double *p;
balance[4]. int i;
Once you store the address of first element in p, p = balance;
you can access array elements using *p, *(p+1), printf( "Array values using pointer\n");
*(p+2) and so on. Below is the example to show
for ( i = 0; i < 5; i++ )
all the concepts discussed above:
{
printf("*(p + %d) : %f\n", i, *(p + i) );
}

printf( "Array values using balance as


address\n");
for ( i = 0; i < 5; i++ ) Array values using pointer
{ *(p + 0) : 1000.000000
printf("*(balance + %d) : %f\n", i, *(balance + *(p + 1) : 2.000000
i) ); *(p + 2) : 3.400000
} *(p + 3) : 17.000000
return 0; *(p + 4) : 50.000000
} Array values using balance as address
*(balance + 0) : 1000.000000
*(balance + 1) : 2.000000
*(balance + 2) : 3.400000
*(balance + 3) : 17.000000
*(balance + 4) : 50.000000

14
4/13/2022

Pointer to Multidimensional
Array
A multidimensional array is of form, a[i][j]. b is the address of the 0th row.
As we know now, name of the array gives its base b+1 is the address of the 1st row.
address. In a[i][j], a will give the base address b+i is the address of the ith row.
of this array, even a+0+0 will also give the base
The size of a row is
address, that is the address of a[0][0] element.
c × sizeof(int) = 5 × sizeof(int) = 5 × 4 = 20
Here is the generalized form for using pointer
bytes
with multidimensional arrays.
where c is the number of columns.

Arithmetic of *(b+i
*(b+i))
If b is the address of the 0th row, *b is the 0th If *(b+i) is the address of the 0th element of
row itself. the ith row, *(b+i) + 1 is the address of the 1st
A row may be viewed as an 1-D array, so *b is the element of the ith row.
address of the 0th element of the 0th row. Similarly *(b+i) + j is the address of the jth
Similarly b+i is the address of the ith row, element of the ith row.
*(b+i) is the ith row, so *(b+i) is the address
of the 0th element of the ith row. The difference between b + i and b is 10i
(bytes), but the difference between *(b + i) + j
If *b is the address of the 0th element of the
0th row, *b + 1 is the address of the 1st element and *(b+i) is 2j (bytes).
of the 0th row.
Similarly *b + j is the address of the jth
element of the 0th row.
The difference between b + 1 and b is 10 (bytes)
but the difference between *b + 1 and *b is the
sizeof(int), 2 (bytes).

*(b + i) + j
b is the address of the 0th row,
b+i is the address of the ith row,
*(b+i) is the address of the 0th element of the
ith row,
*(b+i)+j is the address of the jth element of the
ith row,

15
4/13/2022

*(b + i) + j and &b[i


&b[i][j] *(*(b + i) + j) and b[i
b[i][j]
*(b+i)+j is the address of the jth element of the We know that *(b+i)+j is the address of the jth
ith row, element of the ith row, so
b[i][j] is the jth element of the ith row, a*(*(b + i) + j) is equivalent to b[i][j]
&b[i][j] is the address of the jth element of the
ith row, so
*(b + i) + j is equivalent to &b[i][j]

Pointer and Character strings


*(*(b + i) + j) is equivalent to b[i][j] Pointer can also be used to create strings.
*(b + i) + j is equivalent to &b[i][j] Pointer variables of char type are treated as
*(b[i] + j) is equivalent to b[i][j] string.
b[i] + j is equivalent to &b[i][j] char *str = "Hello";
This creates a string and stores its address in
the pointer variable str.
The pointer str now points to the first character
of the string "Hello".
Another important thing to note that string
created using char pointer can be assigned a
value at runtime.

char *str; char str[6]={‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’};


str = "hello"; //this is Legal printf(“%s”, str);
The content of the string can be printed printf(“%c”, *str);
using printf() and puts(). printf(“%x”, str);
printf("%s", str);
puts(str); Output:
Notice that str is pointer to the string, it is hello
also name of the string. Therefore we do not need
h
to use indirection operator *.
fff0

16
4/13/2022

Array of Pointers
We can also have array of pointers. NOTE: In the second approach memory wastage is
Pointers are very helpful in handling character more, hence it is prefered to use pointer in such
array with rows of varying length. cases.
char *name[3]={ “Baroda”, “Anand”, “Surat” };
Now see same array without using pointer
char name[3][20]= { “Baroda”, “Anand”, “Surat”
};

const int MAX = 4;


int main ()
Value of names[0] = Baroda
{
Value of names[1] = A’bad
char *names[] = { “Baroda”, “A’bad”, “Anand”,
“Surat” }; Value of names[2] = Anand
Value of names[3] = Surat
int i = 0;
for ( i = 0; i < MAX; i++)
{
printf("Value of names[%d] = %s\n", i, names[i]
);
}
return 0;
}

Pointer to functions
It is possible to declare a pointer pointing to a A function pointer can point to a specific
function which can then be used as an argument in function when it is assigned the name of the
another function. function.
A pointer to a function is declared as follows, int sum(int, int);
type (*pointer-name)(parameter); int (*s)(int, int);
Example : s = sum;
int (*sum)(); //legal declaraction of pointer to s is a pointer to a function sum. Now sum can be
function called using function pointer s with the list of
int *sum(); //This is not a declaraction of parameter.
pointer to function s (10, 20);

17
4/13/2022

int sum(int x, int y) Output : 25


{
return x+y;
}
int main( )
{
int (*fp)(int, int);
fp = sum;
int s = fp(10, 15);
printf("Sum is %d",s);
getch();
return 0;
}

Pointer Applications
A. Passing Parameter by Reference B. Accessing Array element
First pointer application is to pass the int main()
variables to function using pass by reference {
scheme.
int a[5] = {1,2,3,4,5};
void swap(int *num1,int *num2)
int *ptr;
{
ptr = a;
int temp;
for(i=0;i<5;i++)
temp = *num1;
{
*num1 = *num2;
printf("%d",*(ptr+i));
*num2 = *num1;
}
}
return(0);
In this scheme we are able to modify value at
}
direct memory location.

C. Dynamic Memory Allocation : D. Reducing size of parameter


Malloc and calloc function is used to allocate struct student
memory dynamically. {
int main() char name[10];
{ int rollno;
char *str; };
str = (char *) malloc(10*sizeof(char)); Suppose we want to pass the above structure to
strcpy(str, "mahesh"); the function then we can pass structure to the
printf("String = %s, Address = %u\n", str, str); function using pointer in order to save memory.
free(str); Suppose we pass actual structure then we need to
allocate (10 + 2 = 12 Bytes) of memory.
return(0);
If we pass pointer then we will require 2 bytes
}
of memory.

18
4/13/2022

Pointer Mistake
E. Some other pointer applications : Mistake 1 : Assigning Value to Pointer Variable
Passing Strings to function int * ptr , m = 100 ;
Provides effective way of implementing ptr = m ; // Error on This Line
the different data structures such as tree, Correction :
graph, linked list ptr is pointer variable which is used to store
the address of the variable.
Pointer Variable “ptr” contain the address of
the variable of type ‘int’ as we have declared
pointer variable with data type ‘int’.
In order to resolve this problem we should assign
address of variable to pointer variable
Write it like this –
ptr = &m ;

Mistake 2 : Assigning Value to Uninitialized Mistake 3 : Not De-referencing Pointer Variable


Pointer De-referencing pointer is process of getting the
We are assigning the value to the pointer value from the address to whom pointer is
variable. We all know that pointer is special pointing to.
kind of variable which is used to store int * ptr , m = 100 ;
the address of another variable. So we can store
ptr = &m ;
only address of the variable to the pointer
variable. printf("%d",ptr);
int * ptr , m = 100 ; *ptr = m ; // Error on In the above example, You will not get any
This Line compiler or run time error but it is considered
as common mistake by novice user to de-reference
We are going to update the value stored at
pointer variable without using asterisk (*)
address pointed by uninitialized pointer
variable. Instead write it as –
int * ptr, m = 100 ,n = 20;
ptr = &n;

Mistake 4 : Assigning Address of Un-initialized Mistake 5 : Comparing Pointers that point to


Variable different objects
int *ptr, m; We cannot compare two pointer variables. Because
ptr = &m; variables may have random memory location. We
cannot compare memory address.
We can assign any valid address to pointer
variable but if you assign the address of un- char str1[10],str2[10];
initialized variable to pointer then it will char *ptr1 = str1;
print garbage value while de-referencing it. char *ptr2 = str2;
if(ptr1 > ptr2) ..... // Error Here
{ .... .... }

19
4/13/2022

Dangling Pointer
Dangling pointers arise when an object is deleted Way 1 : Using free or de-allocating memory
or de-allocated, without modifying the value of #include<stdlib.h>
the pointer, so that the pointer still points to
void main()
the memory location of the de-allocated memory.
{
In short pointer pointing to non-existing memory
location is called dangling pointer. char *ptr = malloc(Constant_Value);
// statements
free (ptr); /* ptr now becomes a dangling pointer
*/
}
We have declared the character pointer in the
first step. After execution of some statements we
have de-allocated memory which is allocated
previously for the pointer.
As soon as memory is de-allocated for pointer,

Problem : If any pointer is pointing the memory Way 2: Out of Scope


address of any variable but after some variable void main()
has deleted from that memory location while
{
pointer is still pointing such memory location.
Such pointer is known as dangling pointer and char *ptr = NULL;
this problem is known as dangling pointer {
problem. char ch;
How to Ensure that Pointer is no Longer Dangling ptr = &ch;
? } /* ptr is now a dangling pointer */
char *ptr = malloc(Constant_Value); }
// statements....... ....... ....... Character Pointer is Declared in the first Step.
free (ptr); /* ptr now becomes a dangling pointer As character variable is non-visible in Outer
*/ Block , then Pointer is Still Pointing to Same
ptr = NULL /* ptr is no more dangling pointer */ Invalid memory location in Outer block , then
} Pointer becomes “Dangling”

Way 3 : Function Call


int * func ( void )
{
int num = 14;
/* ... */
return &num;
}
Attempts to read from the pointer may still
return the correct value (1234) for a while after
calling func, but any functions called thereafter
will overwrite the stack storage allocated for
num with other values and the pointer would no
longer work correctly. If a pointer to num must
be returned, num must have scope beyond the
function—it might be declared as static.

20

You might also like