How does casting uint8* to uint32* work?
c++
Solution
Pointers are merely variables with addresses as their values. That means all pointers have the same size (with is not to be confused with "all pointers' data have the same size", which is not true).
All the information the compiler needs to treat the data pointed to by the pointer is inferred from its type. That means that data pointed to by a `uint32_t` will be treated as 32-bit data, and `uint8_t` will be treated as 8-bit data.
All this information is only kept at compile-time, and the compiler generates the machine code according to the pointer it is dealing with. That means casting from a pointer to the other is only relevant to the compiler, so it knows how to treat the data when generating code. On runtime, nothing changes, no values are copied or moved.
Roughly, you memory layout may look like this:
The bracket part(the size of the data) is a hint to the compiler so it can treat the data as intended by the programmer.
When you cast to a `uint32_t`, your memory layout will roughly look like this:
Now, that are some things you might infer from this:
- Your pointer didn't change at all. It still points to the same location.
- Your memory layout also didn't change. Your data is still there, and so is the other stuff.
- The pointer's data size did change, but this information is only kept at compile-time, so your program's memory layout didn't really change at all.
Finally, consider the implications of accessing this data as 32-bit:
- The "Other Stuff" may be other parts of your own program, and if you modify the value bad things will happen.
- The "Other Stuff" may not belong to your program at all, witch means it will be invading memory that does not belong to it. Again, bad things will happen.
- Maybe the "Other Stuff" are perfectly valid data for the program to access and modify. This should be clearly documented.
Problem
There is a member function here: ``` uint8* CIwTexture::GetTexels() const; ``` How does casting work here if the return value is cast to `uint32*`, for example? How can a pointer to 8-bit data can be cast to 32-bit, if the return value is just 8-bit?