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.

114Part II: Becoming a Functional C++ ProgrammerComparing pointers and housesA pointer is much like a house address. Your house has a unique address.Each byte in memory has an address that is unique. A house address is madeup of both numbers and letters. For example, my address is 123 Main Street.You can store a couch in the house at 123 Main Street — you can store anumber in the byte located at 0x123456. Alternatively, you can take a piece ofpaper and write an address — I don’t know, say, 123 Main Street. You can nowstore a couch at the house with the address written on the piece of paper. Infact, this is the way delivery people work — their job is to deliver a couch tothe address written down on the shipping orders whether it’s 123 Main Streetor not. (I’m not maligning delivery people — they have brains — it’s just thatthis is more or less the way things work.)In C++, the following code snippet finds the address of myHouse and stores acouch at that houseAddress (loosely speaking):House myHouse;House* houseAddress;houseAddress = &myHouse;*houseAddress = couch;In humanspeak, you would say myHouse is a House. houseAddress is theaddress of a House. Assign the address of myHouse to the House pointer,houseAddress. Now store a couch at the house located at the address storedin houseAddress.Having said all that, take a look at the int and int* version of the earlierexample code snippet:int myInt;int* intAddress;intAddress = &myInt;*intAddress = 10;That is, myInt is an int. intAddress is a pointer to an int. Assign theaddress of myInt to the pointer intAddress. Finally, assign 10 to the intthat intAddress points to.Using different types of pointersEvery expression has a type as well as a value. The type of the expressionintVar is pointer to an integer, written as int*. Comparing this with the declarationof pintVar, you see that the types match exactly:int* pintVar = &intVar; // both sides of the assignment are// of type int*

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

Saved successfully!

Ooh no, something went wrong!