C 如何访问timeval结构的字段
我试图打印C 如何访问timeval结构的字段,c,linux,C,Linux,我试图打印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; } 我不断地发现这个错误: request for member 'tv_sec' in someth
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;
}
我不断地发现这个错误:
request for member 'tv_sec' in something not a structure or union.
request for member 'tv_usec' in something not a structure or union.
在非结构或联盟中请求成员“tv_sec”。
在非结构或联盟中请求成员“tv_usec”。
如何修复此问题?您需要使用->运算符,而不是使用。访问字段时的运算符。像这样:
cur->tv\u sec
您还需要分配timeval结构。此时,您正在向函数gettimeofday()传递一个随机指针
因为
cur
是指针。使用
struct timeval cur;
do_gettimeofday(&cur);
在Linux中,
do_gettimeofday()
要求用户预先分配空间。不要只传递一个不指向任何东西的指针!您可以使用malloc()
,但最好的方法是传递堆栈上某个对象的地址。变量cur
是类型为timeval的指针。您需要有一个timeval变量,并将其地址传递给函数。比如:
struct timeval cur;
do_gettimeofday(&cur);
你也需要
#include<linux/time.h>
#包括
它具有结构timeval的定义和函数的声明do_gettimeofday
或者,您可以使用sys/time.h
中的gettimeofday
函数
您需要包含sys/time.h而不是time.h,struct timeval在/usr/include/sys/time.h中定义,而不是在/usr/include/time.h中定义 如果cur在堆栈上,则它不是指针。然后不能使用->操作符。好的,我刚刚试过,我得到了任何错误,说取消引用指向不完整类型的指针。有什么想法吗?@chrisaycock:胡说。在原始代码中,
cur
当然是一个指针,并且肯定在堆栈上(即,具有auto
storage类)。@Gabe不要使用箭头(->),只需坚持点(.)。@Gabe混淆了我的示例代码,其中cur不再是指针。对此很抱歉。该函数位于
中,错误是因为他试图访问指针的成员。关于do\u gettimeofday
,答案仍然有误导性。正如我所说,这是一个在
中声明的函数,该头还定义了struct timeval
。如果你能看看我的下一篇文章,我将非常感激。你有理由使用Do_gettimeofday
而不是便携式POSIXgettimeofday
?在我的例子中,我得到的是“变量”的存储大小直到我从include time.h切换到sys/time.h才知道。非常感谢您的补充。
#include<linux/time.h>