随机函数出错

时间:2017-02-25 12:04:31

标签: c random cuda syntax-error

我的代码出错了 - 我收到错误。“错误:预计会出现”)“。

这个错误来自于 random_ints函数

#include <assert.h>
#include <cuda.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <time.h>


#define N (1024*1024)
#define M (1000000)

void random_ints(int *a, int N)
{
   int i;
   for (i = 0; i < M; ++i)
    a[i] = rand() %5000;
}


__global__ void add(int *a, int *b, int *c) {
        c[blockIdx.x] = a[blockIdx.x] + b[blockIdx.x];
    }


    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
    int size = N * sizeof(int);

    // Alloc space for device copies of a, b, c
    cudaMalloc((void **)&d_a, size);
    cudaMalloc((void **)&d_b, size);
    cudaMalloc((void **)&d_c, size);

    // Alloc space for host copies of a, b, c and setup input values
    a = (int *)malloc(size); random_ints(a, N);
    b = (int *)malloc(size); random_ints(b, N);
    c = (int *)malloc(size);
        // Copy inputs to device
        cudaMemcpy(d_a, a, size, cudaMemcpyHostToDevice);
        cudaMemcpy(d_b, b, size, cudaMemcpyHostToDevice);

        // Launch add() kernel on GPU with N blocks
        add<<<N,1>>>(d_a, d_b, d_c);

        // Copy result back to host
        cudaMemcpy(c, d_c, size, cudaMemcpyDeviceToHost);

        // Cleanup
        free(a); free(b); free(c);
        cudaFree(d_a); cudaFree(d_b); cudaFree(d_c);
        return 0;
    } 

此函数是否需要任何标头,或者只是语法错误?

1 个答案:

答案 0 :(得分:3)

考虑在解释random_ints宏之后如何定义#define

void random_ints(int *a, int (1024*1024))
{
   int i;
   for (i = 0; i < 1000000; ++i)
    a[i] = rand() %5000;
}

显然,你不能像这样在函数的声明中指定数字文字。

好像第二个参数应该是数组的大小。您可以将其称为n,以避免与N

发生冲突
void random_ints(int *a, int n)
{
   int i;
   for (i = 0; i < n; ++i)
       a[i] = rand() %5000;
}