-
Another struct questions
I need to create an unknown number of structs in my application. Does anybody have any recommendations on doing this? I can easily do this inside a function, but then the struct I create inside that function is only available within that function
Code:
structs.h
struct a
{
int a;
int b;
};
Code:
main.c
#include "structs.h"
void funcCreateNewStruct (int i)
{
struct a New[i];
...initialise etc....
}
main
{
int i = 9;
funcCreateNewStruct(i);
...do something with new struct...
}
-
You pass it as an argument to another function.
The function simply needs to take a pointer as argument:
void foo(mystruct* s)
Or
void foo(mystrcut s[])
Both do the same thing, but with different syntax. Remember that when passing an array, you automatically pass a pointer to the first element, so you shouldn't take the address of it.
-
To create an arbitrary number of structs, you use dynamic memory allocation (ie. malloc()).
-
Is this what prelude is saying here
Code:
struct Node *make_node ( void )
{
struct Node new_node = malloc ( sizeof *new_node );
/* Error check and set a default state */
return new_node;
}
or
int make_node ( struct Node **new_node )
{
int rc = EXIT_SUCCESS;
new_node = malloc ( sizeof *new_node );
/* Error check and set a default state */
return rc;
}
Or is it possible to do this
Code:
struct Person {
char *name;
int age;
float height;
};
struct Person people[] = {
{"Prelude", 25, 5.9f},
{"Generic person", 20, 6.0f}
};
and then add another person later?
-
Both work, except the former is for linked lists. The latter is easier if you don't have to alter the data and don't have to add or delete anymore structs to the array.
-
Code:
int make_node ( struct Node **new_node )
{
int rc = EXIT_SUCCESS;
*new_node = malloc ( sizeof(**new_node) );
/* Error check and set a default state */
return rc;
}
Correction in code.
It is not possible to add more stuff at a later time with the last snippet you made, because it's static, as opposed to the first snippets which are dynamic.