Graphics Programs Reference
In-Depth Information
printf("[char pointer] points to %p, which contains the integer %d \n",
char_pointer, *char_pointer);
char_pointer = char_pointer + 1;
}
}
The output below shows the warnings spewed forth from the compiler.
reader@hacking:~/booksrc $ gcc pointer_types2.c
pointer_types2.c: In function `main':
pointer_types2.c:12: warning: assignment from incompatible pointer type
pointer_types2.c:13: warning: assignment from incompatible pointer type
reader@hacking:~/booksrc $
In an attempt to prevent programming mistakes, the compiler gives warn-
ings about pointers that point to incompatible data types. But the compiler
and perhaps the programmer are the only ones that care about a pointer's
type. In the compiled code, a pointer is nothing more than a memory
address, so the compiler will still compile the code if a pointer points to
an incompatible data type—it simply warns the programmer to anticipate
unexpected results.
reader@hacking:~/booksrc $ ./a.out
[integer pointer] points to 0xbffff810, which contains the char 'a'
[integer pointer] points to 0xbffff814, which contains the char 'e'
[integer pointer] points to 0xbffff818, which contains the char '8'
[integer pointer] points to 0xbffff81c, which contains the char '
[integer pointer] points to 0xbffff820, which contains the char '?'
[char pointer] points to 0xbffff7f0, which contains the integer 1
[char pointer] points to 0xbffff7f1, which contains the integer 0
[char pointer] points to 0xbffff7f2, which contains the integer 0
[char pointer] points to 0xbffff7f3, which contains the integer 0
[char pointer] points to 0xbffff7f4, which contains the integer 2
r eader@hacking:~/booksrc $
Even though the int_pointer points to character data that only contains
5 bytes of data, it is still typed as an integer. This means that adding 1 to the
pointer will increment the address by 4 each time. Similarly, the char_pointer 's
address is only incremented by 1 each time, stepping through the 20 bytes of
integer data (five 4-byte integers), one byte at a time. Once again, the little-
endian byte order of the integer data is apparent when the 4-byte integer is
examined one byte at a time. The 4-byte value of 0x00000001 is actually stored
in memory as 0x01 , 0x00 , 0x00 , 0x00 .
There will be situations like this in which you are using a pointer that
points to data with a conflicting type. Since the pointer type determines the
size of the data it points to, it's important that the type is correct. As you can
see in pointer_types3.c below, typecasting is just a way to change the type of a
variable on the fly.
Search WWH ::




Custom Search