user7840026
user7840026

Reputation:

C++ return array without dynamic memory allocation?

I can't find a way to return an array without dynamic memory allocation. I will explain it 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() don't know the size of the array, so i used a struct to solve that problem:

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

Without dynamic memory allocation: I have no idea how to do this. I tried the following things:

Upvotes: 5

Views: 1865

Answers (2)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

You don't need to new anything for this,

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

you can iterate through the list of devices in many different ways, usng iterators for instance.

Normally you don't need pointers at all in c++, if you know how to use references and STL containers, you can do anything you want without a single pointer. There are cases however where it does make sense to use pointers but I doubt this is one of such.

Upvotes: 3

user0042
user0042

Reputation: 8018

In general it is not possible to do so without dynamic memory allocation.
The problems that arise with that (keeping track of the size, correct deallocation, etc.) are common.

These problems you describe are solved in c++ using container classes and dynamic memory management smart pointers.

In your case it would be appropriate to use a std::vector<Device> to represent the list of devices and hide the details and complications of dynamic memory management from you.

Upvotes: 10

Related Questions