我认为一个数组可以分配在gpu前。 __device__ int device_array[100];
而不使用cudaMalloc作为长度是已知的。但是,当我运行下面的代码显示一些不相关的数字。我研究了一本关于cuda的流行书,其中的所有示例都使用了cudaMalloc。一个固定大小的数组可以像这样使用,或者它必须分配给cudaMalloc?cuda固定大小的全局数组
__device__ int device_array[100];
__global__ void kernel() {
device_array[blockIdx.x] = blockIdx.x;
}
void call_kernel(int *host_array) {
kernel<<<100,1>>>();
cudaMemcpy(host_array, device_array, 100 * sizeof(int), cudaMemcpyDeviceToHost);
}
int main() {
int host_array[100];
call_kernel(host_array);
for (int i = 0; i < 100; i++)
cout << host_array[i] << endl;
}
你的代码没有错误检查。可能是'cudaMemcpy'调用失败,但您不知道它,因为您没有检查返回状态。一旦确认运行时发生了错误,问题的根源就会变得明显。 – talonmies
更多[线索](http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#device-variable-qualifier)。如何做错误检查很好地讨论[这里](http://stackoverflow.com/questions/14038589/what-is-the-canonical-way-to-check-for-errors-using-the-cuda-runtime- API)。 –