Gabe
Gabe

Reputation: 49

How to access the fields of a timeval structure

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?

Upvotes: 4

Views: 18366

Answers (4)

Ankit Marothi
Ankit Marothi

Reputation: 1005

You need to include sys/time.h instead of time.h, struct timeval is defined in /usr/include/sys/time.h and not in /usr/include/time.h.

Upvotes: 1

codaddict
codaddict

Reputation: 455062

The variable cur is a pointer of type timeval. You need to have a timeval variable and pass it's address to the function. Something like:

struct timeval cur;
do_gettimeofday(&cur);

You also need

#include<linux/time.h>

which has the definition of the struct timeval and declaration of the function do_gettimeofday.

Alternatively you can use the gettimeofday function from sys/time.h.

Working link

Upvotes: 2

Marc Butler
Marc Butler

Reputation: 1376

You need to use the -> operator rather than then . operator when accessing the fields. Like so: cur->tv_sec.

Also you need to have the timeval structure allocated. At the moment you are passing a random pointer to the function gettimeofday().

struct timeval cur;
gettimeofday(&cur);
printf("%ld.%ld", cur.tv_sec, cur.tv_nsec);

Upvotes: 3

chrisaycock
chrisaycock

Reputation: 37930

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.

Upvotes: 7

Related Questions