# Computer grafics

Solo disponible en BuenasTareas
• Páginas : 8 (1816 palabras )
• Descarga(s) : 0
• Publicado : 14 de febrero de 2012

Vista previa del texto

1

Chapter 1
Pointers, Arrays, and Structures

2

(&X) 1000 (&Y) 1004

X=5 Y=7 Ptr 5 X

(&Ptr) 1200

1000

Pointer illustration

3

(&X) 1000 (&Y) 1004

X = 10 Y=7 Ptr 10 X

(&Ptr) 1200

Ptr = &X =1000

Result of *Ptr=10

4

(&X) 1000 (&Y) 1004

X=5 Y=7 Ptr 5 X

(&Ptr) 1200

Ptr = ?

Uninitialized pointer

5

5 Ptr1 X 7 Ptr2 (a) Y Ptr2 (b) Ptr1

5 X 7 Y Ptr2 Ptr1

(a) Initial state; (b) Ptr1=Ptr2 starting from initial state; (c) *Ptr1=*Ptr2 starting frominitial state

6

&A[0] (1000) &A[1] (1004) &A[2] (1008) &i (1012)

A[0] A[1] A[2] i ...

&A

(5620)

A=1000

Memory model for arrays (assumes 4 byte int); declaration is int A[3]; int i;

7

1 2 3 4

size_t char * char * int

strlen( const char *Str ); strcpy(char *Lhs, const char *Rhs ); strcat( char *Lhs, const char *Rhs ); strcmp( const char *Lhs, const char *Rhs );

Some of the string routines in

8

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

void F( int i ) { int A1[ 10 ]; int *A2 = new int [ 10 ]; ... G( A1 ); G( A2 ); // // // // } On return, all memory associated with A1 is freed Onreturn, only the pointer A2 is freed; 10 ints have leaked delete [ ] A2; // This would fix the leak

Two ways to allocate arrays; one leaks memory

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

10

(a)

A2

(b)

A2

Original

(c)

A2

Original

(d)

A2

Original

Array expansion: (a) starting point: A2 points at 10 integers; (b) after step 1: Original points at the 10 integers; (c) after steps 2 and 3: A2 pointsat 12 integers, the first 10 of which are copied from Original; (d) after step 4: the 10 integers are freed

11

A

Ptr

X

Y

A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]

Pointer arithmetic: X=&A[3]; Y=X+4

12

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

//Test that Strlen1 and Strlen2 give same answer // Source file is ShowProf.cpp #include main( ) { char Str[ 512 ]; while( cin >> Str ) { if( Strlen1( Str ) != Strlen2( Str ) ) cerr

Returns the stored value X is stored

class MemoryCell { public: // Public member functions int Read( ) { return StoredValue; } void Write( int X ) { StoredValue = X; } private: // Private internal datarepresentation int StoredValue; };

A complete declaration of a MemoryCell class

18

Write

StoredV

MemoryCell members: Read and Write are accessible, but StoredValue is hidden