11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 8: Taking a First Look at C++ Pointers 115Similarly, because pintVar is of type int*, the type of *pintVar is int:*pintVar = 10;// both sides of the assignment are// of type intThe type of the thing pointed to by pintVar is int. This is equivalent tosaying that, if houseAddress is the address of a house, the thing pointed atby houseAddress must be a house. Amazing, but true.Pointers to other types of variables are expressed the same way:double doubleVar;double* pdoubleVar = &doubleVar;*pdoubleVar = 10.0;A pointer on a Pentium class machine takes 4 bytes no matter what it pointsto. That is, an address on a Pentium is 4 bytes long, period.Matching pointer types is extremely important. Consider what might happenif the following were allowed:int n1;int* pintVar;pintVar = &n1;*pintVar = 100.0;The second assignment attempts to store the 8-byte double value 100.0 intothe 4-byte space allocated for n1. Actually, this isn’t as bad as it looks — C++is smart enough to demote the constant 100.0 to an int before making theassignment.It is possible to cast one type of variable into another:int iVar;double dVar = 10.0;iVar = (int)dVar;Similarly, it is possible to cast one pointer type into another.int* piVar;double dVar = 10.0;double* pdVar;piVar = (int*)pdVar;Consider, however, what catastrophes can arise if this type of casting aboutof pointers were to get loose. Save a variable into an area of the wrong size,and nearby variables can be wiped out. This is demonstrated graphically inthe following LayoutError program.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!