CO1401 Week 11 Lecture
CO1401 Week 11 Lecture
CO1401 Week 11 Lecture
Programming
Week 11
Pointers
Topic 1
Pointers
2 Programming
Memory
int i;
int j;
cout << &i << endl; // "the address of" i
cout << &j << endl; // "the address of" j
• 0027F988
• 0027F97C
Address
character
pointers variable
0x001C5000 ‘p’
0x001C5004 ‘a’
0x001C5008 ‘n’
Pointers
int* ptr;
What is a pointer?
int* ptr;
002BF8A8
4
002BF89C
7
Pointers
Examples
char ch = 'v';
char* cptr = &ch;
float f = 76.3f;
float* fptr = &f;
24 Programming
Dynamic memory allocation
int main()
{
int* ptr = new(int);
*ptr = 3;
*ptr = *ptr + 4;
cout << *ptr << endl; delete(ptr);
}
Deallocating memory: new
delete (ptr);
Dynamic Memory Allocation
• Be careful:
Memory leaks
33 Programming
Memory leak
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
int main()
{
int* p = new int;
*p = 5;
_CrtDumpMemoryLeaks();
}
Detected memory leaks!
Dumping objects ->
{55} normal block at 0x007F14E8, 4 bytes long.
Data: < > 05 00 00 00
Object dump complete.
Dynamic Memory Allocation: summary
int main()
{
_crtBreakAlloc=-1;
}
Dynamic Memory Allocation: summary