Construct Sensor Packet Placement

#include <iostream>
#include <cstdint>
#include <new>
#include <type_traits>
using namespace std;

// Write your struct and placement new logic here
struct SensorPacket {
    int id;
    int value;
};

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

    // Write your pool construction code here
    alignas(SensorPacket) uint8_t buffer[sizeof(SensorPacket) * 3]; //declare the memory space and size

    SensorPacket * sensor_ptr[3];
    for (int i = 0; i < 3; i++)
    {
        sensor_ptr[i] = new (buffer + i*sizeof(SensorPacket)) SensorPacket{id,value}; //Study this
    }

    cout << sensor_ptr[index]->id << " " << sensor_ptr[index]->value;

    for(int i = 0; i < 3; i++){
        sensor_ptr[i]->~SensorPacket();
    }

    return 0;
}

Solving Approach

 

 

 

 

 

Upvote
Downvote
Loading...

Input

1 50 900

Expected Output

50 900