From 3a1c8e5b00ab96905f4520bbf6db48928f4db2c9 Mon Sep 17 00:00:00 2001 From: Jack Royer <53104608+Garfield1002@users.noreply.github.com> Date: Sun, 8 Aug 2021 14:30:41 +0200 Subject: [PATCH] Use `memcpy` instead of `*(int)*&` The issues with `*(int)*&` are that - It is quite confusing (especially for C++ beginners) - In this case, it is a strict aliasing violation A solution can therefore be to replace it with `memcpy` _This PR comes after a question I asked on [StackOverflow](https://stackoverflow.com/questions/68699806/strange-c-type-casting)_ --- .../tutorial-5-a-textured-cube/index.markdown | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/beginners-tutorials/tutorial-5-a-textured-cube/index.markdown b/beginners-tutorials/tutorial-5-a-textured-cube/index.markdown index 6782760e8..2f5000679 100644 --- a/beginners-tutorials/tutorial-5-a-textured-cube/index.markdown +++ b/beginners-tutorials/tutorial-5-a-textured-cube/index.markdown @@ -95,11 +95,14 @@ if ( header[0]!='B' || header[1]!='M' ){ Now we can read the size of the image, the location of the data in the file, etc : ``` cpp +// add to standard headers +#include + // Read ints from the byte array -dataPos = *(int*)&(header[0x0A]); -imageSize = *(int*)&(header[0x22]); -width = *(int*)&(header[0x12]); -height = *(int*)&(header[0x16]); +memcpy(&dataPos, header + 0xA, sizeof dataPos); +memcpy(&imageSize, header + 0x22, sizeof imageSize); +memcpy(&width, header + 0x12, sizeof width); +memcpy(&height, header + 0x16, sizeof height); ``` We have to make up some info if it's missing :