C Language | Pointers | Pointer Casting
Pointers can be cast to other pointer types. This is useful in low-level code where memory representation matters.
Using Pointer Casting
A pointer type tells the compiler how many bytes to access at once. For example, an array of two 32-bit int values occupies eight bytes and can be inspected through an unsigned char *.
#include <stdio.h>
int main() {
int iCount, iArray[2] = { 0x02040810, 0x20408000 };
unsigned char *cp = (unsigned char *)iArray;
for (iCount = 0; iCount < 8; iCount++)
printf("cp + %d = %d\n", iCount, *(cp + iCount));
return 0;
}
The byte order depends on the system. Intel-compatible CPUs commonly use little-endian storage, where the least significant byte is stored first. Big-endian systems store the most significant byte first.
Pointer-to-pointer casts are allowed, but the programmer is responsible for using them correctly. Converting between pointers and integers is implementation-dependent and should be avoided in portable code.
The null pointer is the important exception. A pointer that does not refer to a valid object can be initialized with NULL.
char *str = NULL;
Compare a pointer with NULL before dereferencing it when validity is uncertain. Dereferencing a null pointer causes undefined behavior.