Dynamic SensorData Allocation

#include <iostream>
using namespace std;

// 1. Define the struct with three integer fields
struct SensorData {
    int x;
    int y;
    int z;
};

int main() {
    int inputX, inputY, inputZ;
    
    // Read values from standard input
    if (!(cin >> inputX >> inputY >> inputZ)) return 0;

    // 2. Dynamically allocate a SensorData object using 'new'
    // This returns a pointer to the allocated memory on the heap
    SensorData* sensorPtr = new SensorData;

    // 3. Store the values in the allocated struct
    // We use the arrow operator (->) to access members via a pointer
    sensorPtr->x = inputX;
    sensorPtr->y = inputY;
    sensorPtr->z = inputZ;

    // 4. Print the values in the required format: x y z
    cout << sensorPtr->x << " " << sensorPtr->y << " " << sensorPtr->z << endl;

    // 5. Free the allocated memory using 'delete'
    // This is crucial to prevent memory leaks in C++
    delete sensorPtr;

    return 0;
}

Solving Approach

 

 

 

 

 

 

Upvote
Downvote
Loading...

Input

3 4 5

Expected Output

3 4 5