Graphics Programs Reference
In-Depth Information
are actually printed with the %d and %c format parameters, notice that the
corresponding printf() arguments must dereference the pointer variables.
This is done using the unary * operator and has been marked above
in bold.
reader@hacking:~/booksrc $ gcc pointer_types.c
reader@hacking:~/booksrc $ ./a.out
[integer pointer] points to 0xbffff7f0, which contains the integer 1
[integer pointer] points to 0xbffff7f4, which contains the integer 2
[integer pointer] points to 0xbffff7f8, which contains the integer 3
[integer pointer] points to 0xbffff7fc, which contains the integer 4
[integer pointer] points to 0xbffff800, which contains the integer 5
[char pointer] points to 0xbffff810, which contains the char 'a'
[char pointer] points to 0xbffff811, which contains the char 'b'
[char pointer] points to 0xbffff812, which contains the char 'c'
[char pointer] points to 0xbffff813, which contains the char 'd'
[char pointer] points to 0xbffff814, which contains the char 'e'
r eader@hacking:~/booksrc $
Even though the same value of 1 is added to int_pointer and char_pointer
in their respective loops, the compiler increments the pointer's addresses by
different amounts. Since a char is only 1 byte, the pointer to the next char
would naturally also be 1 byte over. But since an integer is 4 bytes, a pointer
to the next integer has to be 4 bytes over.
In pointer_types2.c, the pointers are juxtaposed such that the int_pointer
points to the character data and vice versa. The major changes to the code
are marked in bold.
pointer_types2.c
#include <stdio.h>
int main() {
int i;
char char_array[5] = {'a', 'b', 'c', 'd', 'e'};
int int_array[5] = {1, 2, 3, 4, 5};
char *char_pointer;
int *int_pointer;
char_pointer = int_array; // The char_pointer and int_pointer now
int_pointer = char_array; // point to incompatible data types.
for(i=0; i < 5; i++) { // Iterate through the int array with the int_pointer.
printf("[integer pointer] points to %p, which contains the char '%c' \n",
int_pointer, *int_pointer);
int_pointer = int_pointer + 1;
}
for(i=0; i < 5; i++) { // Iterate through the char array with the char_pointer.
Search WWH ::




Custom Search