简体   繁体   English

将指针传递给struct到c中的函数时出错

[英]error when passing pointer to struct to function in 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. 我正在尝试将指向两个struct timevals指针传递给一个函数,该函数将在C程序中输出两者之间的经过时间。 However, even if I dereference these pointers, nvcc throws the error "expression must have class type" (this is a CUDA program). 但是,即使我取消引用这些指针,nvcc也会抛出错误“表达式必须具有类类型”(这是一个CUDA程序)。 Here is the relevant code from main(): 以下是main()的相关代码:

struct timeval begin, end;
if (tflag) { HostStartTimer(&begin) };
// CUDA Kernel execution
if (tflag) { HostStopTimer(&begin, &end); }

And the function definition for HostStopTimer(): 以及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 . 导致错误的行是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. 我没有太多在C中使用结构的经验,更不用说将结构传递给函数的结构,所以我不确定导致错误的是什么。

The . . operator has higher precedence than the * operator, so expressions like *end.tv_sec attempt to first evaluate end.tv_sec (which isn't possible since end is a pointer) and then dereference the result. 运算符的优先级高于*运算符,因此像*end.tv_sec这样的表达式*end.tv_sec尝试计算end.tv_sec (由于end是一个指针,这是不可能的),然后取消引用结果。

You should use (*end).tv_sec or end->tv_sec instead. 您应该使用(*end).tv_secend->tv_sec

You should write elapsed = (((*end).tv_sec - (*begin).tv_sec)*1000000 + (*end).tv_usec - (*begin).tv_usec); 你应该写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 not begin.tv_sec because begin is a pointer to struct. 运算符只能用于结构,而不能用于指向结构的指针,例如: (*begin).tv_sec而不是begin.tv_sec因为begin是指向struct的指针。 the operator -> is just a "shortcut" for the above, for example (*begin).tv_sec is the same as begin->tv_sec operator ->只是上面的“快捷方式”,例如(*begin).tv_sec(*begin).tv_sec begin->tv_sec相同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM