简体   繁体   中英

How to declare a global array of structs and use it in different functions?

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

  1. 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.

  2. 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 freeing servers cause a memory leak?

Hope it is clear, I'm 100% new to C.

is it also possible to declare an array with '[]' (unknown size) and then dynamically initialize it later with malloc?

No. An array must have a knowable size when it is declared. This can be done by explicitly giving it a size in the brackets, or it can be inferred by its initializer. Once its size is set, it will remain that size for its lifetime. malloc , in the strictest sense, doesn't create an "array", but rather returns a pointer to a segment of memory that can be indexed similarly to an array syntactically, but is not truly an array in the same sense as an object declared with [] .

Will not freeing servers cause a memory leak?

Yes, you will have a memory leak if you do not free servers before malloc ing more memory for it without freeing. If you simply need to resize the array without ditching the data, you can use realloc .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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