C语言 我应该如何返回结构指针?



我一直在写一个游戏道具系统,我需要在函数中创建一个结构并返回它的指针,然而,我不知道如何写函数头

我的代码;

typedef struct {
//some member
}Header;
int main()
{
Header *head; //create an pointer to capture the address
head= ItmStartUp();
...     //some code
return 0;
}
Header *header itmStartUp(){ // This line is the root of problem I believe,
//but I don't know how to fix it
Header *head = malloc (100*sizeof(*head)); //create an array of struct
return head;                               //return that address 
}
当我编译代码时,gcc返回:

error: expected '=', ', ', ';', 'asm'或'属性' before 'itmStartUp'|

我一直在引用这些源代码。然而,它不适合我,我该怎么办我想要返回指针?谢谢你

https://cboard.cprogramming.com/c-programming/20380-function-return-pointer-structure.html

返回结构指针

这里出现语法错误:

Header *header itmStartUp()
^^^^^^^___ unexpected stuff

同样,在使用该函数之前,您需要定义该函数的原型。为了清楚起见,示例代码段如下(请阅读注释):

typedef struct {
int var;
} Header;
// Function is expected to return Header* type
Header* itm_startup() {
Header *head = (void *)malloc(sizeof(Header));
head->var = 10;
// Returning the initialized 'head' (the type of Header*)
return head;
}
int main(void) {
// Calling the function to initialize
Header *header = itm_startup();
// Outputting the content of the 'header' pointer
fprintf(stdout, "%dn", header->var);
return 0;
}

最新更新