为什么这不是在Cuda中从设备复制到主机?

时间:2016-09-27 14:04:10

标签: cuda

我正在研究“CUDA by Example”一书的例子。以下代码没有给我答案并且应该正常工作。哪里出错了?

非常感谢您的帮助和解答。

我得到一个输出,读取 在GPU上完成计算会产生答案:& d 按enter键停止

#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <iostream>
#include <stdio.h>

using namespace std;

__global__ void add_integers_cuda(int a, int b, int *c)
{
    *c = a + b;
}

int main(void)
{
    int c;
    int *dev_ptr;

    cudaMalloc((void **)&dev_ptr, sizeof(int)); //allocate sizeof(int) bytes of contiguous memory in the gpu device and return the address of first byte to dev_ptr.

// call the kernel
    add_integers_cuda <<<1,1>>>(2,7,dev_ptr);

    cudaMemcpy(&c, dev_ptr, sizeof(int), cudaMemcpyDeviceToHost);

    printf("Calculation done on GPU yields the answer: &d\n",c );

    cudaFree(dev_ptr);

    printf("Press enter to stop.");
    cin.ignore(255, '\n');

    return 0;

}

1 个答案:

答案 0 :(得分:2)

&d不是正确的printf格式字符:

printf("Calculation done on GPU yields the answer: &d\n",c );

你不会得到你期望的输出。

您应该使用%d代替:

printf("Calculation done on GPU yields the answer: %d\n",c );

这个特殊问题当然与CUDA无关。

如果您刚刚学习并遇到问题,您可能还希望使用cuda-memcheck运行CUDA代码和/或使用proper CUDA error checking。但是,这些都没有指出上述错误。