int main()
{
int n = 1000;
float *d_a;
cudaMalloc(&d_a, n * sizeof(float));
// do something that gives d_a value;
int index = rand() % n; // copy index
float res;
cudaMemcpy(&res, &d_a[index], sizeof(float), cudaMemcpyDeviceToHost);
cudaMemcpy(&res, d_a + index, sizeof(float), cudaMemcpyDeviceToHost);
// Are the above 2 the same and legal ?
cout << res << "\n";
}
return 0;
So I have the following problem. I need to copy exactly 1 element (random index) from the device array. I don't want to copy the entire array because it'd be wasteful.
So, is the above methods safe and conform to CUDA programming guide?
Yes, there is no problem with what you have shown. It is legal and should copy the element you desire from device to host.
Regarding your two methods, they are the same (this is a C++ question, not specific to CUDA).