简体   繁体   中英

initialize array of struct in c

I should store some info in a vector of struct that comes in a little at a time. I know in advance the size of the array. My question is: should I initialize the array with structs that for me represent an invalid input? for example should I do the following:

typedef struct mystruct{
    int ID;
    int xvalue;
} my_struct;

#define NO_INPUT (my_struct) { ID=-1, xvalue=0}

where ID=-1 is an input that doesn't make sense for me. After the definition should I initialize the array to NO_INPUT? What is the best practice? PS Is the #define directive right? Is it compatible with C89 standards? Thanks in advance!

Choosing to initialize storage when it's not really necessary has costs and advantages. C lets you pick your poison.

The cost is touching every allocated byte. For big arrays, this may be expensive. It can hurt CPU cache performance. Some C runtimes don't map malloc ed pages into a program's address space until they're touched. Initializing them defeats this optimization.

The advantage is in mitigating and fixing bugs. Derefing a pointer initialized to NULL causes an immediate seg fault for many modern OS/CPUs. This kind of "fail fast" behavior is a good thing. Uninitialized pointers can point to real data, so the buggy code keeps running, producing bad answers or failing much later. Initialized values also make more sense in debuggers and error messages. They also make it possible to add assertions that a location hasn't been used since initialization in order to detect unintended overwrites.

Due to the advantages, even when the cost of initialization is too high, some programs are designed with a "debugging mode" that either includes extra initialization and checking code with preprocessor directives or enables/disables them dynamically at run time.

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