Construct Sensor Packet Placement

#include <iostream>
#include <new>      // placement new

using namespace std;

// Define struct SensorPacket
struct SensorPacket {
    int id;
    int value;
};

int main() {
    int index, id, value;
    cin >> index >> id >> value;

    // Properly aligned memory pool for exactly 3 SensorPacket objects
    alignas(SensorPacket) unsigned char pool[3][sizeof(SensorPacket)];

    // Construct SensorPacket in the chosen pool slot
    SensorPacket* pkt = new (pool[index]) SensorPacket{ id, value };

    // Print packet data
    cout << pkt->id << " " << pkt->value;

    // (Destructor call omitted intentionally since program ends here,
    // but in real firmware you would call it when reusing the slot)

    return 0;
}

Solving Approach

 

 

 

 

 

Upvote
Downvote
Loading...

Input

1 50 900

Expected Output

50 900