Reputation: 1
I have been writing a game item system, I need to create a struct in function and return the pointer of it, however, I don't know how to write function header
my code;
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
}
when I compiling the code ,gcc return:
error: expected '=', ' , ' , ' ; ', 'asm' or 'attribute' before 'itmStartUp'|
I have been referencing these source. However, it doesn't work for me, what should i do if I want to return the pointer? Thank you
https://cboard.cprogramming.com/c-programming/20380-function-return-pointer-structure.html
Upvotes: 0
Views: 288
Reputation: 7726
You are getting a syntactic error here:
Header *header itmStartUp()
^^^^^^^___ unexpected stuff
Also, you need to define a prototype of the function before taking It into usage. Just to make it clear, an example code segment is as follows (read the comments):
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, "%d\n", header->var);
return 0;
}
Upvotes: 1