Pointer Variables. Sams Publishing Object-Oriented Programming in C++
광고
광고
11 3087 CH10 11/29/01 2:21 PM Page 433
Pointers
433
The
<< insertion operator interprets the addresses in hexadecimal arithmetic, as indicated by the prefix
0x before each number. This is the usual way to show memory addresses. If you aren’t familiar with the hexadecimal number system, don’t worry. All you really need to know is that each variable starts at a unique address. However, you might note in the output that each address differs from the next by exactly 2 bytes. That’s because integers occupy 2 bytes of memory (on a 16-bit system). If we had used variables of type char
, they would have adjacent addresses, since a char occupies 1 byte; and if we had used type double
, the addresses would have differed by 8 bytes.
The addresses appear in descending order because local variables are stored on the stack, which grows downward in memory. If we had used global variables, they would have ascending addresses, since global variables are stored on the heap, which grows upward. Again, you don’t need to worry too much about these considerations, since the compiler keeps track of the details for you.
Don’t confuse the address-of operator
&
, which precedes a variable name in a variable declaration, with the reference operator
&
, which follows the type name in a function prototype or definition. (References were discussed in Chapter 5, “Functions.”)
Pointer Variables
Addresses by themselves are rather limited. It’s nice to know that we can find out where things are in memory, as we did in
VARADDR
, but printing out address values is not all that useful. The potential for increasing our programming power requires an additional idea: variables that
hold address values. We’ve seen variable types that store characters, integers, floating-point numbers, and so on. Addresses are stored similarly. A variable that holds an address value is called a pointer variable, or simply a pointer.
What is the data type of pointer variables? It’s not the same as the variable whose address is being stored; a pointer to int is not type int
. You might think a pointer data type would be called something like pointer or ptr
. However, things are slightly more complicated. The next program,
PTRVAR
, shows the syntax for pointer variables.
// ptrvar.cpp
// pointers (address variables)
#include <iostream> using namespace std; int main()
{ int var1 = 11; //two integer variables int var2 = 22;
10
다운로드
광고