[英]Returning structs in function c
I'm trying to return a struct
from a function. 我正在尝试从函数返回
struct
。 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
. 我试图返回
returnDuo
结构中的内容,但收到错误消息:“ Expected identifier or'('”。如果我使用void
函数,按预期工作,但不返回任何内容,但我无法弄清楚如何返回此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... 我很高兴就如何使它起作用的任何技巧...
it should be 它应该是
struct returnera read(struct returnera returnDuo, struct vara varuArray[])
not 不
struct read(struct returnera returnDuo, struct vara varuArray[])
This is a good case for using a typedef. 这是使用typedef的好例子。 Declaring a typedef to the struct provides a compact single-word name for the struct type.
对结构声明typedef可以为结构类型提供紧凑的单字名称。 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: 请注意,在C ++中(相对于C),您可以简单地单独使用struct的名称:
returnera read(returnera returnDuo, vara varuArray[])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.