[go: up one dir, main page]

0% found this document useful (0 votes)
26 views28 pages

Pointer - Dynamic Memory

The document provides a comprehensive overview of pointers and dynamic memory allocation in C++. It covers the definition, declaration, and usage of pointers, including common mistakes and advantages, as well as dynamic memory management using new and delete operators. Additionally, it explains concepts such as null pointers, pointer to pointer, and passing pointers to functions.

Uploaded by

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

Pointer - Dynamic Memory

The document provides a comprehensive overview of pointers and dynamic memory allocation in C++. It covers the definition, declaration, and usage of pointers, including common mistakes and advantages, as well as dynamic memory management using new and delete operators. Additionally, it explains concepts such as null pointers, pointer to pointer, and passing pointers to functions.

Uploaded by

eric.e.aghedo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 28

POINTER AND DYNAMIC

MEMORY IN C++
CONTENTS

• Addresses in C++ • Pointer to Pointer

• Pointers • Void, Invalid and Null Pointers


• What are pointers? • Common mistakes when working with
• Declaring Pointers Pointers
• Assigning addresses to pointers • Advantages of Pointers
• Getting the value of a variable using
• Dynamic Memory Allocation
pointer
• Operators new and new[]
• Changing values through Pointers
• Operators delete and delete[]
• Pointer Initialization
• Dynamic Memory Allocation in C
• Pointers and Array

• Passing Pointer to Function


Addresses in C++

• To understand the concept of pointer in C++, there Example I


is need to understand how computer stores data.
• When a variable is created in C++ program, the
variable is assigned a space in the computer
memory with a unique address, and the value of
this variable is stored in the assigned location.
• C++ provides a means to know the address of
memory cell where the data is stored and an
opportunity to manipulate the value through the
address instead of the variable name.
• In Example I, mydata is a variable and &mydata
returns the address(0x6ffe0c) of the variable.
Addresses in C++

Example II

NOTE: When a variable is declared, the memory cell needed to


store its value is assigned a specific memory address.
Generally, C++ programs do not actively decide the exact
memory addresses of variables but the Operating System.
However, it may be useful for a program to be able to obtain
the address of a variable during runtime in order to access
data cells that are at a certain position relative to it.
Hence the need to store the addresses of variables.
Pointers
What are Pointers?

• A pointer is simply a variable that holds the address of another


variable.

• It can also be described as a variable pointing to a specific address in a


memory pointed by another variable. It is a symbolic representation of
a memory address.

• Like regular variables, pointers have data types. For example, a pointer
of type integer can hold the address of a variable of type integer. A
pointer of character type can hold the address of a variable of
character type.
Pointers
Declaring Pointers

• Pointers have been described to be variables, therefore they must be declared before use.

• The declaration of C++ takes the following syntax:

datatype *variable_name; OR datatype* variable_name; OR datatype *


variable_name;

• The datatype is the base type of the pointer which must be a valid C++ data type.

• The variable_name should be the name of the pointer variable.

• It is the asterisk that marks the variable as a pointer.

• Below are examples of valid pointer declarations in C++:

int *pAge; // a pointer to integer double *pArea; // a pointer to double

float *pointPI; // a pointer to float char *pSex // a pointer to a


character
Pointers
Assigning addresses to pointers

• Since pointers hold addresses of other variables, such addresses must be assigned to
the pointer variables.
• The address of a variable can be obtained by preceding the name of a variable with an
ampersand sign (&). var
5
• The reference operator(&) also known as address-of operator
1706 returns the variable’s
1707 1708
pointVar
address. 1707
int var; //variable declaration 3002 3003 3004 3005 3006
var = 5;
int* pointVar; //pointer declaration
pointVar = &var; // assign address of var to pointVar pointer
• Here, 5 is assigned to the variable var. And, the address of var is assigned to
pointVar pointer with the statement pointVar = &var
Pointers

Getting the value of a variable using pointer

• Values held by variables could be accessed through the variables


that store their respective addresses.
• This is done by preceding the pointer name with the dereference
operator (*).
int* pointVar, var; //variable and pointer declaration
var = 5;
pointVar = &var; //assign address of var to pointVar
cout << *pointVar << endl; // access value pointed by pointVar
Pointers
Pointers
Changing values through Pointers

• Since a pointer variable points to


the address of a particular
variable, C++ provides a means
of updating the value of such a
variable through the pointer
variable.
• If pVar points to the address of
var, we can change the value of
var by using *pVar.
Pointers
Pointer Initialization

• Pointers as a variable can also be initialized at the point of declaration just like
regular variables.
• That is, Pointers can be initialized to point to specific locations at the very
moment they are defined.
int myvar;
int * myptr = &myvar;
same as:
int myvar;
int * myptr;
myptr = &myvar;
Pointers and Array

• The concept of arrays is related to that of pointers.


• The array name itself denotes the base address of the
array, that is, arrays work very much like pointers to their
first elements.
• This means that ampersand (&) is not needed to assign the
address of an array to a pointer.
• For example:
int myarray [20];
int * mypointer;
mypointer = myarray;
After the above declaration, mypointer and myarray
will be equivalent, and they will share the same properties.
However, a different address can be assigned to mypointer,
but we cannot assign anything to myarray.
mypointer = &myarray; //invalid
Pointers and Array
Passing Pointers to Functions

• C++ allows you to pass a pointer to a function just as values are used.
• Functions can also accept an array declared as a pointer.
• Function call by pointer is a method of passing arguments to a
function that copies the address of an argument into the formal
parameter.
• Inside the function, the address is used to access the actual argument
used in the call.
• This makes the changes made to the parameter to affect the passed
argument: function call by reference
Passing Pointers to Functions
• Example I • Example II
Pointer to Pointer

• C++ allows the use of pointers that point to Assuming the random chosen memory
pointers, which, in turn, point to data (or even locations
for each variable are 7309, 7507 and
to other pointers).
7600. The allocation could be
• The syntax simply requires an asterisk (*) for represented as:
each level of indirection in the declaration of
mydata mypoint1 mypoint2
the pointer.
45 7309 7507
int mydata = 45; 7309 7507 7600

int *mypoint1;
int **mypoint2;
mypoint1 = &mydata;
mypoint2 = &mypoint1;
Null Pointers

• In C++, pointers are allowed to take any address


value, no matter whether there is something at
that address or not.
• Accessing such a pointer causes undefined
behaviour, ranging from an error during runtime to
accessing some random value.
• If there is no exact address that is to be assigned, that
is, a pointer really needs to explicitly point to nowhere; then
the pointer variable can be assigned a NULL, nullptr or
0(zero).
• It should be done during the declaration.
• Such a pointer is known as a null pointer.
The 3 pointer variables are null pointers, meaning that they
• Its value is zero and is defined in many standard
explicitly point to nowhere, and they both actually compare
libraries like iostream.
equal.
NULL POINTER

• Present in some libraries such as: • Note to initialize pointer to nullptr,


• iostream some earlier version of CPP may
• To use it, it must be declared and throw the following error:
initialize • ‘nullptr' was not declared in scope
• int *pointer=NULL; • SOLUTION:
• int *pointer=0; • from tools to compile option
• int *pointer=nullptr; • to settings to code generation
• Note: it is best initialize with NULL • to language standard(-std) from
because some operating systems
• drop down menu pick iso c++11
reserved 0 memory address
NULL POINTER

• Null pointer is a macro


constant defined in some
libraries or header files such as
• <iostream>
• <cstring>
• <clocale>
• <ctime>
• <cwchar>
• <cstddef>
Common mistakes when working with pointers
Suppose we want a pointer myPoint to point to the address of variable myVar
i.e
int myVar, *myPoint;

• Wrong • Correct
myPoint = myVar; myPoint = &myVar;
// myPoint is an address but myVar is
// myPoint is an address and so is
not
&myVar

*myPoint = &myVar;
// &myVar is an address *myPoint = myVar;

// *myPoint is the value stored in // both *myPoint and myVar are


&myVar values
Advantages of using Pointers

• Pointers are variables which store the address of other variables in


C++.
• **More than one variable can be modified and returned by function
using pointers.
• Memory can be dynamically allocated and de-allocated using
pointers.
• Pointers help in simplifying the complexity of the program.
• The execution speed of a program improves by using pointers.
DYNAMIC MEMORY ALLOCATION
Dynamic memory allocation

• In our previous programs, all memory needs were determined before program execution by
defining the variables needed.
• Many times, the programmer is not aware in advance how much memory will be needed to
store a particular information. For example, when the memory needed depends on user input.
• On these cases, programs need to dynamically allocate memory during program execution,
that is a program can allocate and release memory dynamically in line with current memory
requirements. .
• C++ provides new and delete operators to achieve this.
• Memory is allocated at run time within the heap for the variable of a given type new operator.
• delete operator de-allocates memory that was previously allocated by new operator if the
dynamically allocated memory in not in need anymore.
Operators new and new[]

• new operator is usually used to allocate memory to a null pointer by following


it with a type specifier. The syntax is:
pointer = new type
pointer = new type [number_of_elements]
i.e:
int *mypoint; OR int *mypoint = NULL;
mypoint = new int; //allocates memory to contain one single element of type int
mypoint = new int [5]; //allocates a block (an array) of 5 elements of type int
Here, mypoint is a pointer, and thus, the first element pointed to by mypoint can be accessed
either with the expression mypoint[0] or the expression *mypoint (both are equivalent). The
second element can be accessed either with mypoint[1] or *(mypoint +1), and so on...
Operators new and new[] – Exception Handling

• The dynamic memory requested by our program is allocated by the system from the memory
heap. However, computer memory can also be exhausted. Therefore, there are no guarantees
that all requests to allocate memory using operator new are going to be granted by the system.
• C++ provides two standard mechanisms to check if the allocation was successful.
i. A default exception of type bad_alloc is thrown when the allocation fails, if the basic syntax is
used and the program is terminated. i.e
mypoint = new int [5]; // if allocation fails, bad_alloc exception is thrown
ii. Handling the exception by specific handler known as nothrow. When it is used and a memory
allocation fails, instead of throwing a bad_alloc exception or terminating the program, the pointer
returned by new is a null pointer, and the program continues its execution normally., nothrow is
declared in header <new> and as argument for new:
mypoint = new (nothrow) int [5];
Operators delete and delete[]

• In most cases, memory allocated dynamically is only needed during specific periods of time within a
program.
• Once it is no longer needed, it can be freed so that the memory becomes available again for other requests
of dynamic memory.
• The syntax is:
delete pointer;
delete[] pointer;
i.e
delete mypoint;
delete [] mypoint;
• The first statement releases the memory of a single element allocated using new, and the second one
releases the memory allocated for arrays of elements using new and a size in brackets ([]).
Dynamic Memory Allocation in C
THANK YOU

You might also like