0% found this document useful (0 votes)
8 views

pointers

Uploaded by

harsh.becse
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)
8 views

pointers

Uploaded by

harsh.becse
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
You are on page 1/ 27

Pointer In C++

A pointer variable (or pointer in short) is basically the same as


the other variables, which can store a piece of data.
Unlike normal variable which stores a value (such as an int,
double, char, float), a pointer stores a memory address.
Pointers In C++(Cont..)
Pointers are variables that store the address of another variable where the
value resides. That means the pointer is a variable that is used for storing the
address of data.

So, we can categorize variables of two types,


1. Data Variable
2. Address Variable

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

❖ Pointers must be declared before used, just like a normal variable.

❖ The syntax of declaring a pointer is to place a * in front of the name.


❖ A pointer is associated with a type such as int, char, double etc.

Declaring Pointers Example

// Declare a pointer variable called ptr as a pointer of // Declare a pointer variable called iPtr pointing
type to an int (an integer pointer)

type *ptr; int * iPtr;


// or // It will store an address. That address holds an
type* ptr; integer value.
// or
type * ptr; double * dPtr; // Declare a double pointer
Points to Remember:
You must place * in front of each pointer variable.

* applies only to the name that followed.


The * mark indicates that it is not an operator(multiplication) , it is a
pointer variable.
For example:
int *p1, *p2, i; // p1 and p2 are int pointers. i is an int
int* p1, p2, i; // p1 is a int pointer, p2 and i are int
int * p1, * p2, i; // p1 and p2 are int pointers, i is an int

Note: Naming Convention of Pointers: Include a "p" or "ptr" as prefix or suffix, e.g.,
iPtr, numberPtr, pEmployee, pStudent, pCustomer.
Initializing Pointers

1. Use the address-of operator(&) to get the address of a variable.


2. Assign the address to a pointer variable.
For example:
// Declare and Initialize an int variable
int num = 10;

// Declare a pointer variable


int * pNum;

// Assign the address of the num variable to pointer pNum


pNum = #
Why do we need pointers in C++?
Why do we need pointers in C++?

1. Because the code section doesn’t have


direct access to the heap section, so,
we can’t use the heap memory directly
and it will be got wasted.
2. What if stack memory got overflow?
3. In the case of stack overflow we need
to use heap memory.
4. Pointers give indirect access to heap
memory for the code section.
Other important use of pointers:

1. If your program wants to access files residing in secondary storage then


it is not directly possible to access it.
2. But using file pointers you can access the file for your program which
allows you to access it.
3. If your program wants to access network resources then only using
pointers you can access it.
4. To allow your program to access the keyboard, a monitor pointer is
needed. example:
To display HelloWorld in your program you will use cout in C++ which
internally implements a pointer to access the console.
Dynamic Memory Allocation in C++
Allocating memory in the heap section is happening at runtime, not at the compile-time, and
hence Allocating a heap memory is called Dynamic memory Allocation.
To allocate in the heap we need to use the ‘new’ operator;
Dynamic Memory Allocation in C++
❖ Memory allocated in the stack is automatically deallocated once the variable is out of
scope but the same is not true for memory allocated in the heap. We need to
explicitly deallocate memory using the delete operator in C++.
Pointer Arithmetic in C++

Pointer Increment
int array[5]={1,2,3,4,5}
int *ptr = array; //ptr is pointing to the first element of an array

ptr++; //pointer move to the next immediate index.


Pointer Arithmetic in C++

Pointer Decrement:
int array[5]={1,2,3,4,5}
int *ptr=array;
ptr++;
ptr–;

pointer decrement instead it moves to the previous index


Pointer Arithmetic in C++
Pointer Addition by Constant:
int array[5]={1,2,3,4,5}
int *ptr=array;
ptr++;
ptr–;
ptr=ptr+3; //moves the index by 3 and hence now it is pointing to value 4
Pointer Arithmetic in C++
Pointer Subtraction by Constant:
int array[5]={1,2,3,4,5}
int *ptr=array;
ptr++;
ptr–;
ptr=ptr+3;
ptr=ptr-2; //Decrement the index position by 2
Pointer Distance Between Two Pointers
int array[5]={1,2,3,4,5}
int *ptr=array;
ptr++;
ptr–;
ptr=ptr+3;
ptr=ptr-2
int *ptr1=array;
int distance=ptr-ptr1;
Disadvantages of using Pointers in C++
1. Pointers are very dangerous when they are not used properly and
due to pointers Systems may crash means our software or our
program may crash due to run time error.
2. At compile time we may not get the error but at run time we get the
error.
3. Run time errors are very dangerous, the reason is when we deliver
our software to a client so when the user is using our program, then
the user may face the problem during run time that program may
crash.
Disadvantages of using Pointers in C++

Following are the major problems with pointers:

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 pointers are pointers that point to functions in C++. It


stores the memory address of a function so that it can be
used to invoke a function.
2. These pointers can also be used to pass arguments by
reference.

Syntax of Function Pointer:


return_type (*pointer_name)(parameter_list);
Example:
int (*myFunctionPointer)(int, int);
Function Pointer in C++
Syntax of Function Pointer in C++
return_type (*pointer_name)(parameter_list);
Example:
int (*myFunctionPointer)(int, int);

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

new is an operator whereas malloc() is a library function.


new allocates memory and calls constructor for object
initialization. But malloc() allocates memory and does not call
constructor.
Return type of new is exact data type while malloc() returns
void*.
new is faster than malloc() because an operator is always
faster than a function.
calloc() Function in C++
1. The calloc() in is used for the dynamic memory allocation.
2. With the help of calloc() function, we can allocate multiple
blocks of memory with the same size for each block.
3. It is defined inside <cstdlib> header file.
4. calloc() function set each memory block to zero initially.
5. The calloc() function returns a pointer to the start of the
memory block allocated by the function.
6. It returns null pointer if allocation fails.
7. Syntax:
void* calloc(size_t num, size_t size);
Difference between malloc() and calloc()

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 number of arguments in malloc() is 1. The number of arguments in calloc() is 2.

malloc() is faster. calloc() is slower.


malloc() has high time efficiency. calloc() has low time efficiency.

The memory block allocated by malloc() The memory block allocated by calloc() is
has a garbage value. initialized by zero.

malloc() indicates memory allocation. calloc() indicates contiguous allocation.


realloc() function
1. realloc() function is a Dynamic Memory Allocation function that
reallocates main memory.
2. realloc() attempts to shrink or expand the previously allocated block to
size bytes.
3. If size is zero, the memory block is freed and NULL is returned.
4. The block argument points to a memory block previously obtained by
calling malloc(), calloc(), or realloc(). If block is a NULL pointer,
realloc() works just like malloc().
5. realloc() function adjusts the size of the allocated block to size, copying
the contents to a new location if necessary.
Syntax:
void *realloc( void *ptr, size_t new_size );
malloc(), calloc(), realloc() and free()

Function Syntax Description


allocates a block of from memory
malloc void* malloc( size_t size );
heap and returns a pointer
allocates a block of from memory
calloc void* calloc( size_t num, size_t size ); heap, initializes it to zero and
returns a pointer

re-allocates the size of the allocated


realloc void *realloc( void *ptr, size_t new_size ); memory block,, copies the contents
to a new location

Free block of memory blk allocated


free void free( void* ptr );
from memory heap

You might also like