22. Dynamic SensorData Allocation

#include <iostream>
using namespace std;

// Struct representing 3-axis sensor data
struct SensorData {
    int x;
    int y;
    int z;
};

int main() {
    int x, y, z;
    cin >> x >> y >> z;

    SensorData* data = new SensorData; // dynamic allocation

    data->x = x;
    data->y = y;
    data->z = z;

    cout << data->x << " " << data->y << " " << data->z;

    delete data; // free allocated memory

    return 0;
}

Explanation & Logic Summary:

  • A struct groups related sensor fields, which is common in embedded drivers.
  • new SensorData allocates memory on the heap at runtime.
  • The arrow operator (->) is used to access struct members through a pointer.
  • Printing the values confirms correct storage.
  • delete releases heap memory and prevents leaks.

Firmware Relevance & Real-World Context:

  • Sensor drivers often package multi-axis readings into structs.
  • Dynamic allocation is commonly encountered in:
    • RTOS message queues
    • ISR-to-task communication
    • USB / CAN frame construction
    • Heap-based data pipelines
  • Proper memory management is critical for long-running firmware systems.

 

 

 

 

 

Loading...

Input

3 4 5

Expected Output

3 4 5