Академический Документы
Профессиональный Документы
Культура Документы
Pointers
Overview
1.
Pointer Basics
2.
3.
4.
Introduction
Computer Memory
Store 1 byte or 8 bits of data
100
101
102
103
104
105
106
107
108
109
110
Memory Address
100
char ch;
int x;
101
102
103
104
105
106
107
108
109
110
// 1 byte
// 32-bit integer (needs 4 bytes)
100
char ch;
int x;
101
102
103
104
105
106
107
108
109
110
In parameter list
10
Pointer Variables
11
ptr = &y;
1000
ptr 2000
..
.
?
1000
ptr 2000
..
.
1000
12
ptr = &y;
// ptr gets the address of y
cout << *ptr; // Same as cout << y;
*ptr = 10; // Same as y = 10;
13
Pictorial View
p1
?
x
10
1000
10
1004
2000
2004
..
.
?
?
p1
p2
p2
?
14
Pictorial View
p1
p2
x
10
1000
10
1004
..
.
y
5
2000
2004
1000
1004
p1
p2
15
Pictorial View
p1
x
7
p2
y
11
1000
1004
11
..
.
2000
2004
1000
1004
p1
p2
16
Memory View
Pictorial View
p1
x
7
p2
y
11
1000
1004
11
..
.
2000
2004
1000
1000
p1
p2
17
Pictorial View
p1
x
7
p2
y
11
1000
1004
11
..
.
2000
2004
1000
1000
p1
p2
18
p1
*p1 = *p2;
y = 10;
cout << *p2 << endl;
*p1 = 20;
cout << x << " " << y << endl;
p2
19
p1 = &x;
p2 = &y;
*p1 = y;
*p2 = x;
cout << x << " " << y << endl;
cout << *p1 << " " << *p2
<< endl;
p1
p2
20
p1
p2
21
iptr
// Compile-time error
// Compile-time error
23
Same as
int *ptr1;
ptr1 = &y;
int *ptr2 = 0,
// ptr2 stores the address 0
*ptr3 = NULL; // ptr3 stores the address 0
// Correct
// Correct
// Correct
// Compile-time error
// Compile-time error
25
Summary
vs
*p1 = *p2;
26
6.2 Pointer as
Function Parameter
27
Pointers as Parameters
28
// In main()
int x = 3;
int *ptr = &x;
foo(ptr);
cout << x; // Print 0
void foo(int *p) {
*p = 0;
}
// In main()
int x = 3;
int *ptr = &x;
foo(ptr);
cout << x; // Print 0
ptr
x
3
ptr
x
3
29
// In main()
int x = 3;
int *ptr = &x;
foo(ptr);
cout << x; // Print 0
// In main()
int x = 3;
int *ptr = &x;
foo(ptr);
cout << x; // Print 0
ptr
x
0
ptr
x
0
30
31
801
802
foo[0]
803
804
805
806
foo[1]
807
808
809
810
811
812
813
foo[2]
800
801
802
foo[0]
803
804
805
806
foo[1]
807
808
809
810
811
812
813
foo[2]
33
sizeof(type_name)
yields the number of bytes used to represent the value of type
type_name.
e.g., sizeof(int) yields 4
34
e.g.
int arrayA[10], arrayB[100];
double arrayC[2];
cout << arrayA << endl; // Print address of arrayA
cout << arrayB << endl; // Print address of arrayB
cout << arrayC << endl; // Print address of arrayC
36
22
44
55
//
//
//
//
Prints
Prints
Prints
Prints
0
0
1
4
1
1
2
5
2
2
3
6 7 8
return 0;
};
39
40
Dynamic Memory
Management
41
800
801
802
foo[0]
803
804
805
806
foo[1]
807
808
809
810
foo[2]
811
812
813
42
Operator delete
For freeing up the previously allocated
memory space
43
44
// print 2D array
print2DArray(ptr, n, m);
45
Summary
46