How do I return an array of struct from a function?

前端 未结 3 400
滥情空心
滥情空心 2020-12-07 03:54

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

3条回答
  •  离开以前
    2020-12-07 04:36

    first in this code below

    //  n is 0 and n > 2 is false so loop will never execute.
    for(n=0;n>2;n++){
            printf(" name: "); gets(items[n].nome);
            printf(" telefone: "); gets(items[n].telefone);
            printf(" age: "); gets(items[n].idade);
        }
    

    next

     items = fun(); // i don't see items declared anywhere
    

    and here

        printf(" name: "); gets(items[n].nome); // surely its not nome
        printf(" telefone: "); gets(items[n].telefone);
        printf(" age: "); gets(items[n].idade); // neither it is idade
    

    Finally solution, you need to use pointers and allocate memory dynamically

    Your function becomes something like this, ( see the typo )

    //struct Operator fun();
    struct Operador * fun(); // if this is what is correct
    

    Allocation

       //struct Operador items[3];
        struct Operador * items = malloc( 3 * sizeof(struct Operador));
    

    and return call

    //return items[n];
    return items;
    

    and at the end

    free(items);
    

    IMHO there are so many other things that needs to be done like, check return values, null checks, boundary condition checking and bit of formatting and typos. I'll leave it to you.

提交回复
热议问题