Professional Documents
Culture Documents
M. Usman Ghous
Dynamic memory
• In the previous sections, you learned how to declare pointer
variables, how to store the address of a variable into a pointer
variable of the same type as the variable, and how to manipulate data
using pointers.
• However, you learned how to use pointers to manipulate data only
into memory spaces that were created using other variables.
• In other words, the pointers manipulated data into existing memory
spaces
Dynamic memory
• So what is the benefit to using pointers?
• You can access these memory spaces by working with the variables
that were used to create them.
• Now we will learn about the power behind pointers. In particular, you
will learn how to allocate and deallocate memory during program
execution using pointers.
Dynamic memory
• Variables that are created during program execution are called
dynamic variables.
• With the help of pointers, C++ creates dynamic variables. C++
provides two operators, new and delete, to create and destroy
dynamic variables, respectively.
• When a program requires a new variable, the operator new is used.
• When a program no longer needs a dynamic variable, the operator
delete is used.
• In C++, new and delete are reserved words.
New
• The operator new has two forms: one to allocate a single variable and
another to allocate an array of variables.
• The syntax to use the operator new is:
int oned[12];
for(int i=0; i<3; i++){
for(int j=0; j<4 ; j++)
oned[i*4+j] = twod[i][j];
}
• // dry run by students
Pointer to 2D Array
• int b[2][3] = { {1,2,3},{4,5,6} };
• int (*p)[3] = b;
• cout << b << "\t" << &b[0] << endl; //will print address of base of array
• cout << *p << "\t" << b[0] << "\t" << endl;
• cout << b + 1<<endl;
Pointer to 2D Array
• cout << b+1 << "\t" << &b[1] << endl; //will print address second row
base
• cout << (b + 1) << "\t" << b[1] << "\t" << endl;
• cout << b + 1 << endl;