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 开发者_JAVA百科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.
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.
You should use (*end).tv_sec
or end->tv_sec
instead.
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 not begin.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 as begin->tv_sec
精彩评论