Review On Pointers and Dynamic Objects
Review On Pointers and Dynamic Objects
Memory Management
Static Memory Allocation
Memory is allocated at compiling time
Dynamic Memory
Memory is allocated at running time
int a[200];
}
Dynamic object
Memory is acquired by program with an allocation request
new operation
Dynamic objects can exist beyond the function in which they were allocated Object memory is returned by a deallocation request
delete operation
Why pointers?
Dynamic objects are implemented or realized by pointers which are parts of low-level physical memory We dont like it, but can not avoid it.
A pointer is a variable used for storing the address of a memory cell. We can use the pointer to reference this memory cell
Pointers
Memory address:
1020
1024
int a; int* p;
Integer a
100
a
10032
1024
Pointer p
int a = 100; cout << a; Cout << &a;
100
a 100 1024
Dereferencing Operator *
We can access to the value stored in the variable pointed to by preceding the pointer with the star operator (*),
Memory address: 1020 1024 10032
88
100
a
*p
1024
p
int a = 100; int* p = &a; cout << a << endl; cout << &a << endl; cout << p << " " << *p << endl; cout << &p << endl;
gives 100
Pointer to pointer
int a; int* p; int** q;
58
a, *p, and **q are the same object whose value is 58! But q = &a is illegal!
In expressions, an asterisk before a pointer indicates the object the pointer pointed to, called dereferencing
int i = 1, j; int* ptr; // ptr is an int pointer ptr = &i; // ptr points to i j = *ptr + 1; // j is assigned 2 cout << *ptr << j << endl; // display "12"
a; int* b;
int*
a, b;
int k;
Recommended!!!
Summary
* has two usages:
- pointer type definition: int a; int* p; - dereferencing: *p is an integer variable if p = &a; & has two usages: - getting address: p = &a; - reference: int& b a; b is an alternative name for a First application in passing parameters (swap example) int a=10; int b=100; int* p; int* q; P = &a; Q = &b;
p = q; *p = *q;
? ?
int n = 12; j = n; //the value of m is set to 12. But j still refers to m, not to n. cout << value of m = << m <<endl; //value of m printed is 12
n = 36; Cout << value of j = << j << endl; //value of j printed is 12 p = &n;
int x=10;
int& ref;
int& ref = x;
x ref
10
10
} int main() {
char a = 'y'; char b = 'n'; swap(&a, &b); cout << a << b << endl; return 0;
}
Uese pass-by-value of pointers to change variable values C language does not have call by reference!
} int main() {
char a = 'y'; char b = 'n'; swap(a, b); cout << a << b << endl; return 0;
}
y, z are references, only names, not like ptr1, ptr2 that are variables
2 4 6
8
22
2 4 6
8
22
#include <iostream> Using namespace std; void main(){ int a[5] = {2,4,6,8,22}; cout << *a << " " << a[0] << " " << *(&a[0]); ..." } //main
Result is: 2 2 2
p 2 4 6 8 22
dynamic objects
Summary
Static variables (objects) Dynamic variables (objects)
20 static
pa static
20 dynamic
Dynamic array
10
delete two actions: 1. Return the object pointed to 2. Point the pointer p to NULL