1

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?

2
  • if you really mean c++, then it is better to return std::vector<Car> instead of pointers, pointers are c style Commented Oct 2, 2022 at 17:32
  • Please review your assignment, particularly stuff about how a stack works. pop should not return an array. Commented Oct 2, 2022 at 17:40

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.