While processors often have different instructions for “downloading a byte from an address”, “downloading a 16-bit half-word from an address” and “loading a 32-bit word from an address”, as well as for “storing” operations, C uses one the same syntax for loading a byte from an address to load any other size value. Given the statement:
int n = *p;
the compiler can generate code that loads a byte, half-word, or a word from an address in p and stores it in n; if p is * float, it can generate a more complex code sequence to load the floating point value into c, trim it, convert to int, and save the converted value to n. Without knowing the type of p, the compiler cannot know which operation will be suitable.
Similarly, the p++ operator can increment an address in p by one, two, four, or some other number. The amount by which the address is incremented will be determined by the declared type p. If the compiler does not know the type p, it does not know how to configure the address.
You can declare a pointer without specifying the type of thing it points to. The type of such a pointer is void* . However, you must convert void* to a real pointer type before doing anything useful with it; The main utility of void* is that if the pointer is converted to void* , it can be passed as void* by code that does not know anything about the actual type of the pointer. If the pointer is ultimately provided to a code that knows its type, and this code returns the pointer back to that type, the result will be the same as the pointer that was converted to void* .
Code that needs to handle pointers to things that it knows nothing about can often use void* for such purposes, but code that knows about things that the pointer points to should usually point to pointers of the appropriate type.
supercat Dec 05 '13 at 21:41 2013-12-05 21:41
source share