CPP Pointers
CPP Pointers
Basic Concepts
VARIABLES & MEMORY ADDRESSES
• Variables have
• Name
• Address or location in memory
• Content
• Machine code does not use variable names, it uses the variable’s address
• The compiler maps the name to an address
• In a program, the name can represent the address or the content stored at that address
• Name used as an address
• counter = 5;
• Name used as the content
• balance = counter * 10;
• cout << counter << endl;
M E M O RY
M E TA P H O R
MEMORY VIEWED AS AN ARRAY
.
.
.
316
320
324
328
.
.
.
POINTER VARIABLES
• Pointers are variables that hold or store the memory addresses of other
variables or data
• An address is a location in main memory that cannot change
• C++ provides several operators that operate on pointers
POINTER OPERATORS
-> Arrow
POINTER OPERATOR EXAMPLES
i 0x0a000010
int i;
POINTER OPERATOR EXAMPLES
i 0x0a000010
int i;
int* p;
p 0x0a000014
POINTER OPERATOR EXAMPLES
i 123 0x0a000010
int i;
int* p;
i = 123;
p 0x0a000014
POINTER OPERATOR EXAMPLES
i 123 0x0a000010
int i;
int* p;
i = 123;
p = &i;
p 0x0a000010 0x0a000014
DEREFERENCING A POINTER
int i; // restaurant
i 0x0a000010
DEREFERENCING A POINTER
int i; // restaurant
int* p; // Tom’s house
i 0x0a000010
p 0x0a000014
DEREFERENCING A POINTER
int i; // restaurant
int* p; // Tom’s house
i 123 0x0a000010
i = 123;
p 0x0a000014
DEREFERENCING A POINTER
int i; // restaurant
int* p; // Tom’s house
i 123 0x0a000010
i = 123;
p = &i;
p 0x0a000010 0x0a000014
DEREFERENCING A POINTER
int i; // restaurant
int* p; // Tom’s house
i 123 0x0a000010
i = 123;
p = &i
C++ JAVA
C++ JAVA
delete c; // deallocates a single char
delete[] scores; // deallocates an array
delete p; // deallocates one object
POINTER OPERATIONS
Delroy A. Brinkerhoff
RELATIONAL OPERATIONS
int data[] = {
1, 2, 3, 4, 5, 6, 7, 8 p1 1 0x00ffaa00
}; 2 0x00ffaa04
int* p1 = data;
3 0x00ffaa08
int* p2 = p1 + 4; 4 0x00ffaa0c
p2 5 0x00ffaa10
p2 points to 5
6 0x00ffaa14
7 0x00ffaa18
8 0x00ffaa1c
POINTER ARITHMETIC, PART 3
int data[] = {
1, 2, 3, 4, 5, 6, 7, 8 p1 1 0x00ffaa00
}; 2 0x00ffaa04
int* p1 = data;
3 0x00ffaa08
int* p2 = p1 + 4; 4 0x00ffaa0c
p2 5 0x00ffaa10
p2 – p1 is 4 6 0x00ffaa14
7 0x00ffaa18
8 0x00ffaa1c