Switching from a OO language (C#), I would like to know what is the best way to declare a struct array that has application lifetime in C. After 1h struggle (and research for ex. about why not to use typedef, why to repeat struct later, etc.), this code is working:
// declaration
struct server {
char* name;
char* ip_address;
int port;
} server;
struct server *servers; // declaring struct server[] servers; does not work
Then using like this in a function, working as well (after multiple experiments with & and *...):
// nb_servers is known from previous calculation
servers = malloc(nb_servers * sizeof(struct server));
// later in the same function
free(servers);
Questions
Why does declaring the struct array with
[]
not work? Question actually is, is it also possible to declare an array with '[]' (unknown size) and then dynamically initialize it later with malloc and if yes, what is the syntax to do it? Pure syntax question independent of differences in how memory is managed.If I
free(servers)
I can no longer use the values after that. But if I don't, if this function gets called multiple times, will the value of this variable simply be overwritten by the result of the new call? Will not freeingservers
cause a memory leak?
Hope it is clear, I'm 100% new to C.