简体   繁体   中英

How to return array of pointers?

I am new to c++ and I am not sure how to return this kind of variable

int main(){
   list = pop();
}
struct Car{
 int year;
 string type;
};
Car** pop(){
 Car* cars[1000] = {};
 return cars;
}

Could anyone please tell me how should I return the array?

As the declared array has automatic storage duration then it will not be alive after exiting the function.

So you need either to allocate it dynamically or to declare it with the storage class specifier static as for example

static Car* cars[1000] = {};

Functions may not have the return type that is an array type. You can return a pointer either to the first element of an array as for example

Car** pop( void ){
    static Car* cars[1000] = { 0 };
    return cars;
}

or to the whole array like

Car ( * pop( void ) )[1000] {
    static Car* cars[1000] = { 0 };
    return &cars;
}

or can return a reference to the array

Car ( & pop( void ) )[1000] {
    static Car* cars[1000] = {};
    return cars;
}

In C++ you can't return arrays, In fact you can't even assign an array to a variable as you could do with Python's lists and JS arrays.
In C++ Arrays are just a contiguous memory blocks of same datatype.
For example, see the below code example:

int a[10];
cout << a;

This snippet would only print(a[0]), You see the identifier of the array is basically pointer to the base or first element.
You can't directly return an array however you could return the identifier and the following elements can be accessed using the pointer notation

*(a+0) // For Base Element
*(a+1) // For Second Element
*(a+2) // For Third Element
...
*(a+9) // For Last Element

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM