将指向结构体的指针传递给c中的函数时出错
我试图将指向两个 struct timevals 的指针传递给一个函数,该函数将在 C 程序中输出两者之间经过的时间。但是,即使我取消引用这些指针,nvcc 也会抛出错误“表达式必须具有类类型”(这是一个 CUDA 程序)。以下是 main() 中的相关代码:
struct timeval begin, end;
if (tflag) { HostStartTimer(&begin) };
// CUDA Kernel execution
if (tflag) { HostStopTimer(&begin, &end); }
HostStopTimer() 的函数定义:
void HostStopTimer(struct timeval *begin, stuct timeval *end) {
long elapsed;
gettimeofday(end, NULL);
elapsed = ((*end.tv_sec - *begin.tv_sec)*1000000 + *end.tv_usec - *begin.tv_usec);
printf("Host elapsed time: %ldus\n", elapsed);
}
导致错误的行是对 elapsed
的赋值。我没有太多在 C 中使用结构的经验,更不用说将结构指针传递给函数了,所以我不确定是什么导致了错误。
I'm trying to pass pointers to two struct timevals
to a function that would output the elapsed time between the two in a C program. However, even if I dereference these pointers, nvcc throws the error "expression must have class type" (this is a CUDA program). Here is the relevant code from main():
struct timeval begin, end;
if (tflag) { HostStartTimer(&begin) };
// CUDA Kernel execution
if (tflag) { HostStopTimer(&begin, &end); }
And the function definition for HostStopTimer():
void HostStopTimer(struct timeval *begin, stuct timeval *end) {
long elapsed;
gettimeofday(end, NULL);
elapsed = ((*end.tv_sec - *begin.tv_sec)*1000000 + *end.tv_usec - *begin.tv_usec);
printf("Host elapsed time: %ldus\n", elapsed);
}
The line causing the error is the assignment to elapsed
. I don't have much experience using structs in C, much less passing pointers to structs to functions, so I'm not sure what is causing the error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
.
运算符的优先级高于*
运算符,因此像*end.tv_sec
这样的表达式会尝试首先计算end.tv_sec< /code> (这是不可能的,因为
end
是一个指针),然后取消引用结果。您应该使用
(*end).tv_sec
或end->tv_sec
代替。The
.
operator has higher precedence than the*
operator, so expressions like*end.tv_sec
attempt to first evaluateend.tv_sec
(which isn't possible sinceend
is a pointer) and then dereference the result.You should use
(*end).tv_sec
orend->tv_sec
instead.您应该编写
elapsed = (((*end).tv_sec - (*begin).tv_sec)*1000000 + (*end).tv_usec - (*begin).tv_usec);
或使用 <代码>-> 运算符。.
运算符只能用于结构体,不能用于指向结构体的指针,例如:(*begin).tv_sec
而不是begin.tv_sec
因为 begin 是一个指向结构体的指针。运算符->
只是上述内容的“快捷方式”,例如(*begin).tv_sec
与begin->tv_sec< 相同/代码>
You should write
elapsed = (((*end).tv_sec - (*begin).tv_sec)*1000000 + (*end).tv_usec - (*begin).tv_usec);
or use the->
operator.the
.
operator can be used only on structs, not on pointers to structs, for example:(*begin).tv_sec
and notbegin.tv_sec
because begin is a pointer to struct. the operator->
is just a "shortcut" for the above, for example(*begin).tv_sec
is the same asbegin->tv_sec