How can I reinitialize a timeval structure from time.h?
I understand that I can reset so that both elements of the structure are zero, but is there any other method that I skip?
A completely correct and portable (albeit C99) way to zero-initialize arbitrary (possibly aggregate) types:
myTime = (struct timeval){0};
This works even for structures containing pointers and floating-point members, even if the implementation does not use all-zero-bits as representations for null pointers and floating-point zeros.
memset may work on your platform, but this is actually not a recommended (portable) approach ...
memset
:
struct timeval myTime; myTime = (struct timeval){ 0 };
memset , struct timeval , all-zeroes .
struct timeval
. , POSIX , time_t , C , - .
time_t
, , , , , ... , memset .
, , struct timeval , , , C90 ++
static struct timeval init_timeval; // or whatever you want to call it // ... myTime = init_timeval;
R. answer Nemo answer, NULL , . , struct timeval , , , struct timeval.
The disadvantage to it compared to other answers is that it requires a static or global variable to be defined. The advantage is that it will work with compilers other than C99.
If you are looking for a single line, I think you can also use memset for the job:
struct timeval myTime; /* snip ... myTime is now initialized to something */ memset(&myTime, 0, sizeof(timeval)); // Reinitialized to zero
You can use memset, then you would also need to reset any platform related members.