文档介绍:Copyright 1996 by Addison-Wesley pany 1
Chapter 1
Pointers, Arrays, and Structures
Copyright 1996 by Addison-Wesley pany 2
(&X) 1000 X = 5
(&Y) 1004 Y = 7 5
Ptr X
(&Ptr) 1200 1000
Pointer illustration
Copyright 1996 by Addison-Wesley pany 3
(&X) 1000 X = 10
(&Y) 1004 Y = 7 10
Ptr X
(&Ptr) 1200 Ptr = &X = 1000
Result of *Ptr=10
Copyright 1996 by Addison-Wesley pany 4
(&X) 1000 X = 5
(&Y) 1004 Y = 7 5
Ptr X
(&Ptr) 1200 Ptr = ?
Uninitialized pointer
Copyright 1996 by Addison-Wesley pany 5
5 5
Ptr1 X Ptr1 X Ptr1
7 7
Ptr2 Y Ptr2 Y Ptr2
(a) (b)
(a) Initial state; (b) Ptr1=Ptr2 starting from initial state;
(c) *Ptr1=*Ptr2 starting from initial state
Copyright 1996 by Addison-Wesley pany 6
&A[0] (1000) A[0]
&A[1] (1004) A[1]
&A[2] (1008) A[2]
&i (1012) i
...
&A (5620) A=1000
Memory model for arrays (assumes 4 byte int); declara-
tion is int A[3]; int i;
Copyright 1996 by Addison-Wesley pany 7
1 size_t strlen( const char *Str );
2 char * strcpy( char *Lhs, const char *Rhs );
3 char * strcat( char *Lhs, const char *Rhs );
4 int strcmp( const char *Lhs, const char *Rhs );
Some of the string routines in <>
Copyright 1996 by Addison-Wesley pany 8
1 void
2 F( int i )
3 {
4 int A1[ 10 ];
5 int *A2 = new int [ 10 ];
6
7 ...
8 G( A1 );
9 G( A2 );
10
11 // On return, all memory associated with A1 is freed
12 // On return, only the pointer A2 is freed;
13 // 10 ints have leaked
14 // delete [ ] A2; // This would fix the leak
15 }
Two ways to allocate arrays; one leaks memory
Copyright 1996 by Addison-Wesley pany 9
A1 A2
int *Original = A2; // 1. Save pointer to the original
A2 = new int [ 12 ]; // 2. Have A2 point at more memory
for( int i = 0; i < 10; i++ ) // 3. Copy the old data over
A2[ i ] = Original[ i ];
delete [ ] Original; // 4. Recycle the original array
Memory reclamation
Copyright 1996 by Addison-Wesley pany 10
A2
(a)
A2
(b)
Or