Returning structs in function c

2020-04-10 04:07发布

问题:

I'm trying to return a struct from a function. It looks like this..

struct read(struct returnera returnDuo, struct vara varuArray[]) { 
     char varunr[LISTNUMBER], varunamn[LISTNUMBER];
     FILE *varuLista;
     varuLista = fopen(returnDuo.filnamn, "r");
     if(varuLista!=NULL) {
         while(fscanf(varuLista,"%s\t%s\t%d\n",varunr, varunamn, 
                      &varuArray[returnDuo.antalVaror].lagerSaldo) == 3){ 
            strncpy(varuArray[returnDuo.antalVaror].varuNr,varunr,5);
            strncpy(varuArray[returnDuo.antalVaror].varuNamn,varunamn,30);
            returnDuo.antalVaror++;
        } 
        printf("Filen är laddad..\n"); 
        kommaVidare();
     }
     else {
        printf("Filen hittades inte, skapar en tom fil"); kommaVidare();
     }
     fclose(varuLista);
     return returnDuo;
 }

I'm trying to return the content in the returnDuo struct but I get the error message: "Expected identifier or '('". If I use void function its working as expected without returning anything but I cant figure out how to return this struct.

This is how I setup the structs.

struct vara {
    char varuNr[5];
    char varuNamn[50];
    int lagerSaldo;
};

struct returnera {
    int antalVaror;
    char filnamn[LISTNUMBER];
};

And how I setup them up in main.

struct vara varuArray[SIZE];

struct returnera returnDuo = {0,"0"};

I gladly take any tips on how to get this to work...

回答1:

it should be

struct returnera read(struct returnera returnDuo, struct vara varuArray[])

not

struct read(struct returnera returnDuo, struct vara varuArray[])


回答2:

This is a good case for using a typedef. Declaring a typedef to the struct provides a compact single-word name for the struct type. Example:

#include "stdio.h"

typedef struct Item_Struct {
    int val;
} Item;

Item Update( Item item, int val )
{
    item.val = val;
    return item;
}

int main( int argc, char** argv )
{
    Item item;
    printf( "Item -> %i\n", Update(item,4).val ); // Prints "Item -> 4"
    return 0;
}

Note that in C++ (as opposed to C) you can simply use the name of the struct by itself:

returnera read(returnera returnDuo, vara varuArray[])