How do I return an array of struct from a function? Here's my work; it's pretty simple to understand. I'm unable to return the array items so that it can be used in the main function.
#include<stdio.h>
#include<string.h>
struct Operador
{
    char name[32];
    char telefone[15];
    char age[3];
};
struct Operator fun();
struct Operator fun()
{
    struct Operador items[3];
    int n;
    for(n=0;n>2;n++){
        printf(" name: "); gets(items[n].nome);
        printf(" telefone: "); gets(items[n].telefone);
        printf(" age: "); gets(items[n].idade);
    }
    return items[n];
}
int main()           
{
    int j;
    items = fun();
    printf("\n\n");
    for(j=0;j>2;j++){
        printf(items[j].name);
        printf(items[j].telefone);
        printf(items[j].age);
        printf("\n\n");
    }
}
                struct Operator fun()
{
    struct Operador items[3];
     ...
    return items[n];
}
You cannot return a local-defined array of structs defined in an automatic variable. And what you do in your case, you return items[n] for an n where items was not initialized.
you can return an array only if you allocate it on the heap and you can do something so:
struct Operator *fun(int k)
{
    struct Operador *items = malloc(sizeof(struct Operator) * k);
    int n;
    for(n=0;n<k;n++){
        printf(" name: "); gets(items[n].nome);
        printf(" telefone: "); gets(items[n].telefone);
        printf(" age: "); gets(items[n].idade);
    }
    return items;
}
                        If you want to return an array of structs from a function in C, you need to heap allocate them and return a pointer; because, in C, every stack allocated variable is gone after the function returns. So you can do the following:
struct Operator* fun() {
    struct Operator* pItems = (Operator*)calloc(3, sizeof(struct Operator));
    // process items
     return pItems;
 }
After you are done with using the array returned from this function, don't forget to use free on it so that the memory is not being held unnecessarily.
// in main
struct Operator* pItems = fun();
// do stuff with items
free(pItems);
Edit: Add free step.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With