You are on page 1of 60

POINTERS

• Pointer is a special type of variable used to


store the memory location address of a
variable.
• Declaring Pointers (Creating Pointers)
• declaration of pointer variable is similar to the
creation of normal variable but the name is
prefixed with * symbol. We use the following
syntax to declare a pointer variable...
datatype *pointerName ;
• Example Code
• int *ptr ;
Assigning Address to Pointer
• To assign address to a pointer variable we use
assignment operator with the following
syntax...
• pointerVariableName = & variableName ;
• Example Program |
• int a, *ptr ;
• In the above declaration, variable "a" is a
normal integer variable and variable "ptr" is an
integer pointer variable. If we want to assign
the address of variable "a" to pointer variable
"ptr" we use the following statement...
• Example Code
• ptr = &a ;
Initialization of C Pointer variable

• Pointer Initialization is the process of assigning


address of a variable to a pointer variable.
Pointer variable can only contain address of a
variable of the 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
• #include<stdio.h>
• void main()
•{
• int a = 10;
• int *ptr; //pointer declaration
• ptr = &a; //pointer initialization
• }
Pointers Arithmetic Operations in
C
Pointer variables are used to store the address
of variables. Address of any variable is an
unsigned integer value i.e., it is a numerical
value. So we can perform arithmetic operations
on pointer values. But when we perform
arithmetic operations on pointer variable, the
result depends on the amount of memory
required by the variable to which the pointer is
pointing.
AddressAtPointer +
( NumberToBeAdd *
BytesOfMemoryRequiredByDataty
• void main()
•{ pe )
• int a, *intPtr ; float b, *floatPtr ; double c, *doublePtr ;
• intPtr = &a ; // Asume address of a is 1000
• floatPtr = &b ; // Asume address of b is 2000
• doublePtr = &c ; // Asume address of c is 3000
• intPtr = intPtr + 3 ; // intPtr = 1000 + ( 3 * 2 )
• floatPtr = floatPtr + 2 ; //floatPtr = 2000 + ( 2 * 4 )
• doublePtr = doublePtr + 5 ; // doublePtr = 3000 + ( 5 * 6 )
• printf("intPtr value : %u\n", intPtr) ;
• printf("floatPtr value : %u\n", floatPtr) ;
• printf("doublePtr value : %u", doublePtr) ;
• }
AddressAtPointer -
( NumberToBeAdd *
BytesOfMemoryRequiredByDataty
• void main() pe )
•{
• int a, *intPtr ; float b, *floatPtr ; double c,
*doublePtr ;
• intPtr = &a ; // Asume address of a is 1000
• floatPtr = &b ; // Asume address of b is 2000
• doublePtr = &c ; // Asume address of c is 3000
• intPtr = intPtr - 3 ; // intPtr = 1000 - ( 3 * 2 )
• floatPtr = floatPtr - 2 ; //
• floatPtr = 2000 - ( 2 * 4 )
AddressAtPointer +
NumberOfBytesRequiresByDatatyp
e
• void main()
• { int a, *intPtr ; float b, *floatPtr ; double c,
*doublePtr ;
• intPtr = &a ; // Asume address of a is 1000
• floatPtr = &b ; // Asume address of b is 2000
• doublePtr = &c ; // Asume address of c is 3000
• intPtr++ ; // intPtr = 1000 + 2
• floatPtr++ ; // floatPtr = 2000 + 4
• doublePtr++ ; // doublePtr = 3000 + 6
• printf("intPtr value : %u\n", intPtr) ;
AddressAtPointer -
NumberOfBytesRequiresByDatatyp
e
• void main()
• { int a, *intPtr ; float b, *floatPtr ; double c,
*doublePtr ;
• intPtr = &a ; // Asume address of a is 1000
• floatPtr = &b ; // Asume address of b is 2000
• doublePtr = &c ; // Asume address of c is 3000
• intPtr-- ; // intPtr = 1000 - 2
• floatPtr-- ; // floatPtr = 2000 - 4
• doublePtr-- ; // doublePtr = 3000 - 6
• printf("intPtr value : %u\n", intPtr) ;
COMPARISION OF POINTERS
• Comparison of Pointers
• The comparison operation is perform between
the pointers of same datatype only. In c
programming language, we can use all
comparison operators (relational operators)
with pointers.
• We can't perform multiplication and division
operations on pointers.
Pointers to Pointers in C

• C programming language also provides a


pointer variable to store the address of another
pointer variable. This type of pointer variable is
called a pointer to pointer variable. Sometimes
we also call it a double pointer. We use the
following syntax for creating pointer to
pointer…
• datatype **pointerName ;
• Example Program
• int **ptr ;
• MOST IMPORTANT POINTS TO BE
REMEMBERED
• To store the address of normal variable we use
single pointer variable
• To store the address of single pointer variable
we use double pointer variable
#include<stdio.h>
• int main()
•{
• int a ; int *ptr1 ; int **ptr2 ; int ***ptr3 ;
• ptr1 = &a ;
• ptr2 = &ptr1 ;
• ptr3 = &ptr2 ;
printf("\nAddress of normal variable 'a' =
%u\n", ptr1) ; printf("Address of pointer variable
'*ptr1' = %u\n", ptr2) ;
Pointers to void in C

• In the c programming language, pointer to void


is the concept of defining a pointer variable
that is independent of data type. In C
programming language, a void pointer is a
pointer variable used to store the address of a
variable of any datatype. That means single
void pointer can be used to store the address
of integer variable, float variable, character
variable, double variable or any structure
variable. We use the keyword "void" to create
• Example Code
• void *ptr;
• Here, "ptr" is a void pointer variable which is
used to store the address of any datatype
variable.
• MOST IMPORTANT POINTS TO BE
REMEMBERED
• void pointer stores the address of any datatype
variable.
• Example Program
• #include<stdio.h>
• int main()
• {
• int a ; float b ; char c ; void *ptr ;
• ptr = &a ;
• printf(“Address of integer variable ‘a’ = %u\n”,
ptr) ;
• ptr = &b ;
• printf(“Address of float variable ‘b' = %u\n”,
ptr) ; ptr = &c ;
• printf(“Address of character variable ‘c’ =
%u\n”, ptr) ;
• return 0;
Pointers to Arrays in C

In the c programming language, when we


declare an array the compiler allocate the
required amount of memory and also creates a
constant pointer with array name and stores the
base address of that pointer in it. The address of
the first element of an array is called as base
address of that array.

• The array name itself acts as a pointer to the


first element of that array. Consider the
• Example Program
• #include<stdio.h>
• int main()
•{
• int marks[6] = {89, 45, 58, 72, 90, 93} ;
• int *ptr ;
• ptr = marks ;
• printf(“Base Address of 'marks' array = %u\n”,
ptr) ;
•}
• MOST IMPORTANT POINTS TO BE
REMEMBERED
• An array name is a constant pointer.
• We can use the array name to access the
address and value of all the elements of that
array.
• Since array name is a constant pointer we can't
modify its value.
Pointers for Functions in C

• In the c programming language, there are two


ways to pass parameters to functions. They are
as follows...
• Call by Value
• Call By Reference
• We use pointer variables as formal parameters
in call by reference parameter passing method.
• In case of call by reference parameter passing
method, the address of actual parameters is
passed as arguments from the calling function
Example - Swapping of two
variable values using Call by
Reference
• #include<stdio.h>
• void swap(int *, int *) ;
• void main()
• {
• int a = 10, b = 20 ;
• printf(“Before swap : a = %d and b = %d\n", a,
b) ;
• swap(&a, &b) ;
• printf(“After swap : a = %d and b = %d\n", a, b)
;
• }
• NULL Pointer
• NULL Pointer is a pointer which is pointing to
nothing. In case, if we don’t have address to be
assigned to a pointer, then we can simply use
NULL.
• #include <stdio.h>
• int main()
•{
•     // Null Pointer
•     int *ptr = NULL;
•       
•     printf("The value of ptr is %p", ptr);
•     return 0;
•}
• Output :
• Important Points
• NULL vs Uninitialized pointer – An uninitialized
pointer stores an undefined value. A null
pointer stores a defined value, but one that is
defined by the environment to not be a valid
address for any member or object.
• NULL vs Void Pointer – Null pointer is a value,
while void pointer is a type
Dynamic Memory Allocation in C

• In C programming language, when we declare


variables memory is allocated in space called
stack. The memory allocated in the stack is
fixed at the time of compilation and remains
until the end of the program execution. When
we create an array, we must specify the size at
the time of the declaration itself and it can not
be changed during the program execution. This
is a major problem when we do not know the
number of values to be stored in an array. To
• Dynamic memory allocation is the process of
allocating the memory manually at the time of
program execution.
• We use pre-defined or standard library
functions to allocate memory dynamically.
There are FOUR standard library functions that
are defined in the header file known as
"stdlib.h". They are as follows...
• malloc()
• calloc()
• malloc()
• malloc() is the standard library function used to
allocate a memory block of specified number
of bytes and returns void pointer. The void
pointer can be casted to any datatype. If
malloc() function unable to allocate memory
due to any reason it returns NULL pointer.
• Syntax
• void* malloc(size_in_bytes)
• #include<stdio.h>
• #include<conio.h>
• int main ()
• { char *title;
• title = (char *) malloc(15);
• strcpy(title, "c programming");
• printf("String = %s, Address = %u\n", title,
title);
• return(0);
•}
The name "calloc" stands for contiguous allocation.
The malloc() function allocates memory and leaves the memory
uninitialized. Whereas, the calloc() function allocates memory
and initializes all bits to zero.
• calloc()
• calloc() is the standard library function used to
allocate multiple memory blocks of the
specified number of bytes and initializes them
to ZERO. calloc() function returns void pointer.
If calloc() function unable to allocate memory
due to any reason it returns a NULL pointer.
Generally, calloc() is used to allocate memory
for array and structure. calloc() function takes
two arguments and they are 1. The number of
• Example Program for calloc().
• #include<stdio.h> #include<conio.h> int main
() { int i, n; int *ptr; printf("Number of blocks to
be created:"); scanf("%d",&n); ptr =
(int*)calloc(n, sizeof(int)); printf("Enter %d
numbers:\n",n); for( i=0 ; i < n ; i++ )
{ scanf("%d",&ptr[i]); } printf("The numbers
entered are: "); for( i=0 ; i < n ; i++ ) { printf("%d
",ptr[i]); } return(0); }
• realloc()
• realloc() is the standard library function used to
modify the size of memory blocks that were
previously allocated using malloc() or calloc().
realloc() function returns void pointer. If
calloc() function unable to allocate memory
due to any reason it returns NULL pointer.
• Syntax
• void* realloc(*pointer,
new_size_of_each_block_in_bytes)
• Example
• Example Program for realloc().
• #include<stdio.h> #include<conio.h> int main
() { char *title; title = (char *) malloc(15);
strcpy(title, "c programming"); printf("Before
modification : String = %s, Address = %u\n",
title, title); title = (char*) realloc(title, 30);
strcpy(title,"C Programming Language");
printf("After modification : String = %s, Address
= %u\n", title, title); return(0); }
• free()
• free() is the standard library function used to
deallocate memory block that was previously
allocated using malloc() or calloc(). free()
function returns void pointer. When free()
function is used with memory allocated that
was created using calloc(), all the blocks are get
deallocated.
• Syntax
• void free(*pointer)
• Example
• Example Program for free().
• #include<stdio.h> #include<conio.h> int main
() { char *title; title = (char *) malloc(15);
strcpy(title, "c programming"); printf("Before
modification : String = %s, Address = %u\n",
title, title); title = (char*) realloc(title, 30);
strcpy(title,"C Programming Language");
printf("After modification : String = %s, Address
= %u\n", title, title); free(title); return(0); }
Dangling pointer
• Dangling pointer
• A pointer pointing to a memory location that
has been deleted (or freed) is called dangling
pointer. There are three different ways where
Pointer acts as dangling pointer
• / Deallocating a memory pointed by ptr causes
• // dangling pointer
• #include <stdlib.h>
• #include <stdio.h>
• int main()
•{
•     int *ptr = (int *)malloc(sizeof(int));
•   
•     // After below free call, ptr becomes a 
•     // dangling pointer
• Wild pointer
• A pointer which has not been initialized to
anything (not even NULL) is known as wild
pointer. The pointer may be initialized to a non-
NULL garbage value that may not be a valid
address.
• int main()
•{
•     int *p;  /* wild pointer */
•   
•     int x = 10;
•   
•     // p is not a wild pointer now
•     p = &x;
•   
•     return 0;
Auto storage class

• The variables defined using auto storage class


are called as local variables. Auto stands for
automatic storage class. A variable is in auto
storage class by default if it is not explicitly
specified.
• The scope of an auto variable is limited with
the particular block only. Once the control goes
out of the block, the access is destroyed. This
means only the block in which the auto
variable is declared can access it.

#include<stdio.h>

int main()

{

int i;

auto char c;

float f;

printf("i = %d\tc = %c\tf = %f",i,c,f);

return 0;

}
Extern storage class

• Extern stands for external storage class. Extern


storage class is used when we have global
functions or variables which are shared
between two or more files.
• Keyword extern is used to declaring a global
variable or function in another file to provide
the reference of variable or function which
have been already defined in the original file.
• The variables defined using an extern keyword
are called as global variables. These variables
• #include <stdio.h>
• extern i;
• main()
•{
• printf("value of the external integer is = %d\n",
i);
• Return 0;
•}
• Static storage class
• The static variables are used within function/
file as local static variables. They can also be
used as a global variable
• Static local variable is a local variable that
retains and stores its value between function
calls or block and remains visible only to the
function or block in which it is defined.
• Static global variables are global variables
visible only to the file in which it is declared.
• #include <stdio.h> /* function declaration */
void next(void); static int counter = 7; /* global
variable */ main() { while(counter<10) { next();
counter++; } return 0;} void next( void ) { /*
function definition */ static int iteration =
13; /* local static variable */ iteration ++;
printf("iteration=%d and counter= %d\n",
iteration, counter);}
• Result:
• iteration=14 and counter= 7 iteration=15 and
counter= 8 iteration=16 and counter= 9
• Register storage class
• You can use the register storage class when you
want to store local variables within functions or
blocks in CPU registers instead of RAM to have
quick access to these variables. For example,
"counters" are a good candidate to be stored in
the register.
• Example: register int age;
• The keyword register is used to declare a
register storage class. The variables declared
using register storage class has lifespan
throughout the program.
• It is similar to the auto storage class. The
variable is limited to the particular block. The
only difference is that the variables declared
using register storage class are stored inside
CPU registers instead of a memory. Register
has faster access than that of the main
• #include <stdio.h> /* function declaration */
main() { {register int weight; int
*ptr=&weight ;/*it produces an error when the
compilation occurs ,we cannot get a memory
location when dealing with CPU register*/} }
• OUTPUT:
• error: address of register variable 'weight'
requested
• A storage class is used to represent additional
information about a variable.
• Storage class represents the scope and lifespan
of a variable.
• It also tells who can access a variable and from
where?
• Auto, extern, register, static are the four
storage classes in 'C'.
• auto is used for a local variable defined within
a block or function
Storag Declar Storag Defaul Scope Lifeti
e Class ation e t me
Initial
Value
auto Inside Memo Unpre Within Within
a ry dictabl the the
functi e functi functi
on/blo on/blo on/blo
ck ck ck
registe Inside CPU Garba Within Within
r a Regist ge the the
functi ers functi functi
on/blo on/blo on/blo
ck ck ck
extern Outsid Memo Zero Entire progra
e all ry the file m
functi and runtim
ons other e
files
where
the
variabl
e is
declar
ed as
extern
Static Inside Memo Zero Within progra
(local) a ry the m
functi functi runtim
on/blo on/blo e
ck ck
Static Outsid Memo Zero Global progra
(global e all ry m
) functi runtim
ons e

You might also like