我正在通过NVIDIA提供的培训幻灯片学习CUDA。他们有一个示例程序,显示如何添加两个整数。代码如下:
#include <stdio.h>
__global__ void add(int *a, int *b, int *c) {
*c = *a+*b;
}
int main(void) {
int a, b, c; // Host copies of a, b, c
int *d_a, *d_b, *d_c; // Device copies of a, b, c
size_t size = sizeof(int);
//Allocate space for device copies of a, b, c
cudaMalloc((void**)&d_a, size);
cudaMalloc((void**)&d_b, size);
cudaMalloc((void**)&d_c, size);
//Setup input values
a = 2;
b = 7;
c = -3;
//Copy inputs to device
cudaMemcpy(d_a, &a, size, cudaMemcpyHostToDevice);
cudaMemcpy(d_b, &b, size, cudaMemcpyHostToDevice);
//Launch add() kernel on GPU
add<<<1,1>>>(d_a, d_b, d_c);
//Copy result back to host
cudaMemcpy(&c, d_c, size, cudaMemcpyDeviceToHost);
//Cleanup
cudaFree(d_a); cudaFree(d_b); cudaFree(d_c);
printf("For a = %d, b = %d, we get a + b = %d\n", a, b, c);
return 0;
}
但是当我运行程序时,输出是: “对于a = 2,b = 7,我们得到a + b = -3”
意思是c的值没有变化!
我做错了什么?
答案 0 :(得分:1)
您的代码正确地将c的值打印为9.您需要澄清运行此代码的环境。