pointers
pointers
Data Variable is used for storing data whereas the Address Variable is used for
storing address.
int x = 10; // x is data variable
int *Ptr; // Ptr is an address variable
Pointers In C++(Cont..)
Declaring Pointers
// Declare a pointer variable called ptr as a pointer of // Declare a pointer variable called iPtr pointing
type to an int (an integer pointer)
Note: Naming Convention of Pointers: Include a "p" or "ptr" as prefix or suffix, e.g.,
iPtr, numberPtr, pEmployee, pStudent, pCustomer.
Initializing Pointers
Pointer Increment
int array[5]={1,2,3,4,5}
int *ptr = array; //ptr is pointing to the first element of an array
Pointer Decrement:
int array[5]={1,2,3,4,5}
int *ptr=array;
ptr++;
ptr–;
1. Uninitialized Pointers
2. The pointer may cause a memory leak
3. Dangling Pointers
Dangling pointer
❖ If two pointers point to the same memory location and pointer 1
deallocates the memory but pointer 2 trying to access the memory
thinking it is available is called dangling pointer.
Function Pointer in C++
1. Function Declaration:
void (*fp)();
2. Initialization:
fp = display()
3. Calling Function:
(*fp)()
Dynamic Memory Allocation
malloc() is a library function of stdlib.h and it was used in C
language to allocate memory for N blocks at run time, it can
also be used in C++ programming language.
Whenever a program needs memory to declare at run time
we can use this function.
new is an operator in C++ programming language, it is also
used to declare memory for N blocks at run time.
Syntax for the malloc() function:
void* malloc(size_t size);
1. Here, void* is a pointer to the allocated memory block.
2. size_t parameter specifies the size in bytes to the size of the
allocated memory block.
Differences between new operator and malloc() function
malloc() calloc()
malloc() function creates a single block of calloc() function assigns multiple blocks of
memory of a specific size. memory to a single variable.
The memory block allocated by malloc() The memory block allocated by calloc() is
has a garbage value. initialized by zero.