Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the fields of a timeval structure

Tags:

c

linux

I'm trying to print the values in a struct timeval variable as follows:

int main()  
{  

    struct timeval *cur;  
    do_gettimeofday(cur);  
    printf("Here is the time of day: %ld %ld", cur.tv_sec, cur.tv_usec);  

    return 0;  
}  

I keep getting this error:

request for member 'tv_sec' in something not a structure or union.  
request for member 'tv_usec' in something not a structure or union.

How can I fix this?

like image 391
Gabe Avatar asked Dec 13 '22 18:12

Gabe


1 Answers

Because cur is a pointer. Use

struct timeval cur;
do_gettimeofday(&cur);

In Linux, do_gettimeofday() requires that the user pre-allocate the space. Do NOT just pass a pointer that is not pointing to anything! You could use malloc(), but your best bet is just to pass the address of something on the stack.

like image 112
chrisaycock Avatar answered Jan 05 '23 00:01

chrisaycock