How to access time structure fields

I am 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?

+4
source share
4 answers

Because cur is a pointer. Use

 struct timeval cur; do_gettimeofday(&cur); 

On Linux, do_gettimeofday() requires the user to pre-allocate space. DO NOT just pass a pointer that does not point to anything! You can use malloc() , but it's best to just pass the address of something on the stack.

+7
source

You need to use the β†’ operator, not then. when accessing the fields. For example: cur->tv_sec .

You also need to highlight the allocated timeval structure. You are currently passing a random pointer to the gettimeofday () function.

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

The variable cur is a pointer type timeval. You need to have a variable and pass its address to the function. Sort of:

 struct timeval cur; do_gettimeofday(&cur); 

You also need

 #include<linux/time.h> 

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

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

Working link

+2
source

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.

+1
source

All Articles