CUDA矩阵加法出错

sbaban 2015-09-14 11:32:21

#include<cuda_runtime_api.h>
#include<stdio.h>
__global__ void add(int a[2][2], int b[2][2], int c[2][2])
{
int i = blockIdx.x*blockDim.x + threadIdx.x;
int j = blockIdx.y*blockDim.y + threadIdx.y;
if (i < 2 && j < 2)
{
c[i][j] = a[i][j] + b[i][j];
}
}
int main()
{
int i, j, k;
int a[2][2] = { 1, 2, 3, 4 };
int b[2][2] = { 10, 20, 30, 40 };
int c[2][2] = { 0 };

cudaError_t error = cudaSuccess;

int device_a[2][2], device_b[2][2], device_c[2][2];
error = cudaMalloc((void **)&device_a, sizeof(int)* 4);
error = cudaMalloc((void **)&device_b, sizeof(int)* 4);
error = cudaMalloc((void **)&device_c, sizeof(int)*4);

cudaMemcpy(device_a,a, sizeof(int)* 4, cudaMemcpyHostToDevice);
cudaMemcpy(device_b,b, sizeof(int)* 4, cudaMemcpyHostToDevice);

// dim3 threadsPerBlock(1, 1);
// dim3 numBlocks(2 / threadsPerBlock.x, 2 / threadsPerBlock.y);

add << <1, 4 >> >(device_a, device_b, device_c);

cudaMemcpy(c, device_c, sizeof(int)* 4, cudaMemcpyDeviceToHost);

for (i = 0; i < 2; i++){printf("\n");for (j = 0; j < 2; j++)printf("%4d", c[i][j]);}

return 0;
}

请问为什么结果显示是0 ,哪里出问题了
...全文
266 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
gundamzzj 2015-11-18
  • 打赏
  • 举报
回复
把 global函数 改成 __global__ void add(int*a int*b,int*c) 然后main 函数里你应该声明三个指针 然后为他们动态分配内存: int *device_a, *device_b, *device_c;
fgg1991 2015-09-17
  • 打赏
  • 举报
回复
读了一下 代码感觉没啥问题 你把参数改成int*在host里给他们分配空间再试?
sbaban 2015-09-17
  • 打赏
  • 举报
回复
怎么改,能具体说下吗

579

社区成员

发帖
与我相关
我的任务
社区描述
CUDA™是一种由NVIDIA推出的通用并行计算架构,该架构使GPU能够解决复杂的计算问题。 它包含了CUDA指令集架构(ISA)以及GPU内部的并行计算引擎。
社区管理员
  • CUDA编程社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧