Notes
C Plus Plus
C Plus Plus
  • Roadmap
    • ๐Ÿ›ฃ๏ธC Plus Plus: Docs
  • Build
    • ๐Ÿ”ฅBuild Process
    • ๐Ÿ”งConnect multiple C++ Files
  • Code
    • โฎ๏ธPre-Processors
      • #include
      • #define
      • #ifdef
      • #pragma
      • Predefined Macros
    • LValue and RValue
    • ๐Ÿช…Data Types
      • Enum
      • TypeDef
      • const in c++
      • extern vs inline
    • ๐ŸŽญCasting
    • ๐Ÿ”ƒOperator overloading
      • Available Operators
      • Examples of operator overloading
    • ๐Ÿ—บ๏ธNamespace
      • Namespace Example
      • Using directive
    • ๐Ÿ•ต๏ธHeader File
      • For C++ Classes
    • ๐Ÿ—๏ธStructure
      • Struct vs Class
      • Public vs Private inheritance
    • ๐ŸขClasses
      • Friend Function
      • Copy Constructor
      • Explicit Constructor
      • Move Constructor
        • Move Semantics
      • Other constructors
      • Virtual functions
      • Pure virtual function
      • Other function declaration
      • const function vs final function
  • Memory
    • ๐Ÿง Memory Introduction
    • โœจHeap and Stack
    • ๐ŸŽฏPointers
      • Dangling Pointer
      • 'this' Pointer
      • Function Pointer
      • Smart Pointers
        • Unique Pointer
        • Shared Pointer
        • Weak Pointer
      • Reference count
    • ๐Ÿ‘จโ€๐ŸญHelper function
    • ๐ŸกVector [ArrayList]
      • Custom vector, part 1
      • Custom vector, part 2
      • Custom vector, part 3
      • std::vector
    • โ™ป๏ธUnion
      • Type Punning
      • Type Punning, part 2
      • Type Punning, part 3
      • Union, part 1
      • Union, Part 2
  • Thread
    • ๐ŸงตThreading
      • std::thread
      • Detach a thread
  • Misc
    • ๐Ÿ—‚๏ธExecution Order
    • ๐Ÿง Print memory
Powered by GitBook
On this page
  1. Memory
  2. Union

Type Punning, part 2

In last session, we converted double to int, now we will extend on this with a struct implementation.

Here is what it would look like:

#include <iostream>

struct Vector
{
    int a, b;
};

void printMem(void *location)
{
    unsigned char const *pos = (unsigned char const *)location;

    for (int i = 0; i < 20; i++) {
        printf("|%2.2x| ", pos[i]);
    }
    
    printf("\n");
}

int main(int argc, char const *argv[])
{
    Vector v = {1 ,2};
    printMem(&v);

    int* v2 = (int*) &v;
    std::cout << "a: " << v2[0] << ", b: " << v2[1] << std::endl;

    return 0;
}

Try it here.

// Output
|01| |00| |00| |00| |02| |00| |00| |00| |00| |26| |87| |5e| |29| |fe| |f1| |3b| |00| |00| |00| |00| 
a: 1, b: 2

Let's see how it works:

  1. We have a structs, Vector.

  2. Vector contains 2 integers a and b.

  3. If we look at its memory allocation, it would be similar to an array with two int.

  4. It means, we can read this struct as an array with indexes.

  5. Hence, if we get pointer to a in struct, we can index on it to read value of b from its memory.

PreviousType PunningNextType Punning, part 3

Last updated 10 months ago

โ™ป๏ธ