繁体   English   中英

由函数初始化的结构体数组

[英]Array of structs initialized by function

我想做的是创建一个结构数组,并通过一个函数对其进行初始化,但是我遇到了一些错误,

lab2.c:20:2: error: declaration of anonymous struct must be a definition
    struct *person users[] = userInput();
    ^
lab2.c:20:2: warning: declaration does not declare anything[-Wmissing-declarations]
    struct *person users[] = userInput();
    ^~~~~~
lab2.c:24:1: error: declaration of anonymous struct must be a definition
    struct * userInput() {
    ^
lab2.c:48:2: error: expected identifier or '('
    }
    ^
1 warning and 3 errors generated.

下面是我的代码,在精简版本中,如果需要更多信息,请告诉我,我对C还是很陌生,所以我猜这对我来说显然是一个错误。

int main() {
    struct person users = userInput();
    return 0;
}

struct * userInput() {
     struct person users[30];
     ...do stuff to struct here...
     return *users;
}

在声明指向已标记struct的指针时,星号位于标记之后,而不是关键字struct 要声明动态分配的数组,请使用不带方括号的星号:

struct person *users = userInput();

返回指向局部变量的指针是未定义的行为:

struct person users[30];
// This is wrong
return *users;

使用动态分配的内存代替:

struct person *users = malloc(sizeof(struct user) * 30);

完成数据处理后,您需要在调用方中free它。

好的,您的代码有很多问题。 当您执行以下操作时,忽略语法内容:

struct person users[30]

该内存是临时的,并在函数返回时释放。 最有可能给您带来分段错误或数据损坏。 您需要类似:

#include <stdlib.h>

typedef struct { char name[30]; int age; char gender; } person;

person* userInput();

int main() {
    person* users = userInput();
    return 0;
}

person* userInput() {
    person* users = malloc( 30 * sizeof(person) );
    /* Init stuff here */
    return users;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM