Another Look at Pointer Variables

While pointer variables have a special role, they too are just places in memory used to store a particular kind of data (in their case, the addresses of other pieces of data). Like ordinary variables, they have a size and a location in memory (Figure 9.7). And as with ordinary variables, you can use the address-of operator to find a pointer variable's address.

Figure 9.7. The value stored in a pointer variable (x and y) is the memory address of another variable (a and b).


Our next example shows you how these locations and sizes look on your machine. It makes use of the sizeof() function, which returns the number of bytes used by a particular variable.

To list pointer sizes and locations

1.
Open pointer2.c (Script 9.2) in your text editor or IDE.

2.
Add four more printf() function calls (Script 9.3):

printf("Size of a: %d
", sizeof(a));
printf("Size of b: %d
", sizeof(b));
printf("Size of x: %d
", sizeof(x));
printf("Size of y: %d
", sizeof(y));

Script 9.3. Character and integer variables occupy different amounts of memory, which we demonstrate by using the sizeof() function.


Each of these lines will print the memory size of a variable. It will show the space taken up by both the initial variables as well as their pointers.

3.
Save the file as pointer3.c.

4.
Compile and debug as necessary.

5.
Run the application (Figure 9.8).

Figure 9.8. Different data types use different amounts (in bytes) of memory.


You can see that the char variable takes less memory (1 byte) than either the integer or the pointer variables. You can also see that the pointer variable for a char address requires the same amount of space as the pointer variable that holds an integer address.

✓ Tips

  • The previous example illustrates an important point: when you define a pointer variable to hold some object's address, the system allocates space for that address. It does not allocate space for the object itself. So for example if you define a pointer to an integer, you do not get any space to store the integer. You get space (usually 4 bytes) to store an integer's address, but you still need to define (and thereby allocate space for) that integer separately. We will get back to this in the next chapter, where you will learn how to explicitly ask the system for the allocation of a block of memory.

  • The address values in the output of the previous examples were in hexadecimal format. A handy way to convert from hexa-decimal to decimal numbers is to use Google. Just search for something like 0xbffff96c in decimal and Google will return the result 0xbffff96c = 3 221 223 788.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset