c - 随机函数的错误

标签 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;
    } 

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

最佳答案

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

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;
}

关于c - 随机函数的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42455833/

相关文章:

c# - 特殊随机数

c - 在C中生成不相等的随机数

c++ - 在一次操作中进行多个矩阵-矩阵乘法

python - Python/C API 中 Python 胶囊的安全和防御编码视角

c - 如何在 C 中将一个共享内存拆分为 3 个不同大小的 mmap 指针?

php - 生成一个介于 1 和 x 之间的随机数,其中较小的数字比较大的数字更有可能

c++ - OpenCL 或 CUDA 走哪条路?

c++ - CUB 选择是否有返回的索引

c - 读取文件错误

c++ - 使用 GCC 在可执行文件中嵌入资源