Graphics Programs Reference
In-Depth Information
As discussed earlier, dividing the integer 13 by 5 will round down to the
incorrect answer of 2, even if this value is being stored into a floating-point
variable. However, if these integer variables are typecast into floats, they will
be treated as such. This allows for the correct calculation of 2.6.
This example is illustrative, but where typecasting really shines is when it
is used with pointer variables. Even though a pointer is just a memory address,
the C compiler still demands a data type for every pointer. One reason for
this is to try to limit programming errors. An integer pointer should only
point to integer data, while a character pointer should only point to char-
acter data. Another reason is for pointer arithmetic. An integer is four bytes
in size, while a character only takes up a single byte. The pointer_types.c pro-
gram will demonstrate and explain these concepts further. This code uses the
format parameter %p to output memory addresses. This is shorthand meant
for displaying pointers and is basically equivalent to 0x%08x .
pointer_types.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 = char_array;
int_pointer = int_array;
for(i=0; i < 5; i++) { // Iterate through the int array with the int_pointer.
printf("[integer pointer] points to %p, which contains the integer %d\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.
printf("[char pointer] points to %p, which contains the char '%c'\n",
char_pointer, *char_pointer);
char_pointer = char_pointer + 1;
}
}
In this code two arrays are defined in memory—one containing integer
data and the other containing character data. Two pointers are also defined,
one with the integer data type and one with the character data type, and they
are set to point at the start of the corresponding data arrays. Two separate for
loops iterate through the arrays using pointer arithmetic to adjust the pointer
to point at the next value. In the loops, when the integer and character values
Search WWH ::




Custom Search