Home > Back-end >  How to return array of pointers?
How to return array of pointers?

Time:10-03

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?

CodePudding user response:

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;
}

CodePudding user response:

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
  • Related