Pointer (computer Programming) - Typed Pointers and Casting

Typed Pointers and Casting

In many languages, pointers have the additional restriction that the object they point to has a specific type. For example, a pointer may be declared to point to an integer; the language will then attempt to prevent the programmer from pointing it to objects which are not integers, such as floating-point numbers, eliminating some errors.

For example, in C

int *money; char *bags;

money would be an integer pointer and bags would be a char pointer. The following would yield a compiler warning of "assignment from incompatible pointer type" under GCC

bags = money;

because money and bags were declared with different types. To suppress the compiler warning, it must be made explicit that you do indeed wish to make the assignment by typecasting it

bags = (char *)money;

which says to cast the integer pointer of money to a char pointer and assign to bags.

A 2005 draft of the C standard requires that casting a pointer derived from one type to one of another type should maintain the alignment correctness for both types (6.3.2.3 Pointers, par. 7):

char *external_buffer = "abcdef"; int *internal_data; internal_data = (int *)external_buffer; // UNDEFINED BEHAVIOUR if "the resulting pointer // is not correctly aligned"

In languages that allow pointer arithmetic, arithmetic on pointers takes into account the size of the type. For example, adding an integer number to a pointer produces another pointer that points to an address that is higher by that number times the size of the type. This allows us to easily compute the address of elements of an array of a given type, as was shown in the C arrays example above. When a pointer of one type is cast to another type of a different size, the programmer should expect that pointer arithmetic will be calculated differently. In C, for example, if the money array starts at 0x2000 and sizeof(int) is 4 bytes whereas sizeof(char) is 1 bytes, then (money+1) will point to 0x2004 but (bags+1) will point to 0x2001. Other risks of casting include loss of data when "wide" data is written to "narrow" locations (e.g. bags=65537;), unexpected results when bit-shifting values, and comparison problems, especially with signed vs unsigned values.

Although it is impossible in general to determine at compile-time which casts are safe, some languages store run-time type information which can be used to confirm that these dangerous casts are valid at runtime. Other languages merely accept a conservative approximation of safe casts, or none at all.

Read more about this topic:  Pointer (computer Programming)

Famous quotes containing the word casting:

    For the gods, though slow to see, see well, whenever a man casting aside worship turns folly.
    Sophocles (497–406/5 B.C.)