C ++ returned array without heap allocation?

I cannot find a way to return the array without dynamically allocating memory. I will explain this in detail using an example:
With dynamic memory allocation :

Device* getConnectedDevices() {
    // scan for devices.
    Device *connectedDevices = new Device[deviceCount]; // Dynamically allocate memory for the Devices
    // Get for each device an ID
    return connectedDevices;
}
void doSomething() {
    // some code
    // I need a list with all the connected devices!!
    Device *connectedDevices;
    connectedDevices = getConnectedDevices();
    // do something with the array
}

      

doSomething () doesn't know the size of the array, so I used a struct to solve this problem:

struct deviceArray {
    Device* devices;
    int deviceCount;
};

      


No heap allocation: I don't know how to do this. I've tried the following things:

  • Follow this link. Problem: we don't know the size of the array before scanning.
  • Return without dynamic memory allocation (local variable). Problem: The object no longer exists (of course).
+3


source to share


2 answers


In general, this cannot be done without heap allocation.
The problems that arise with this (keeping track of size, correct release, etc.) are common.

These problems that you describe are addressed in C ++ using container classes and dynamic memory management smart pointers .



In your case, it would be wise to use it std::vector<Device>

to present a list of devices and hide the details and complexities of heap management from you.

+9


source


You don't need new

anything for this,

std::vector<Device> getConnectedDevices()
{
    std::vector<Device> devices;
    // Fill `devices' with devices.push_back()
    return devices;
}

      



you can iterate over the list of devices in different ways, like iterators .

You usually don't need pointers at all in C ++, if you know how to use STL references and containers, you can do whatever you want without a single pointer. However, there are cases where it makes sense to use pointers, but I doubt this is one of those.

+3


source







All Articles