Linux 如何访问 timeval 结构的字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4029923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access the fields of a timeval structure
提问by Gabe
I'm trying to print the values in a struct timeval
variable as follows:
我正在尝试struct timeval
按如下方式打印变量中的值:
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?
我怎样才能解决这个问题?
回答by Marc Butler
You need to use the -> operator rather than then . operator when accessing the fields. Like so: cur->tv_sec
.
您需要使用 -> 运算符而不是 then 。访问字段时的运算符。像这样: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().
您还需要分配 timeval 结构。目前,您正在传递一个指向函数 gettimeofday() 的随机指针。
struct timeval cur;
gettimeofday(&cur);
printf("%ld.%ld", cur.tv_sec, cur.tv_nsec);
回答by chrisaycock
Because cur
is a pointer. Use
因为cur
是一个指针。用
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.
在 Linux 中,do_gettimeofday()
要求用户预先分配空间。不要只传递一个不指向任何东西的指针!您可以使用malloc()
,但最好的办法是传递堆栈中某些内容的地址。
回答by codaddict
The variable cur
is a pointerof type timeval. You need to have a timeval variableand pass it's address to the function. Something like:
该变量cur
是一个timeval 类型的指针。您需要有一个 timeval变量并将其地址传递给函数。就像是:
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
.
它具有结构 timeval 的定义和函数的声明do_gettimeofday
。
Alternatively you can use the gettimeofday
function from sys/time.h
.
另外,您可以使用gettimeofday
从功能sys/time.h
。
回答by Ankit Marothi
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.
您需要包含 sys/time.h 而不是 time.h,struct timeval 定义在 /usr/include/sys/time.h 而不是 /usr/include/time.h。