2017-02-25 40 views
-1

我有錯誤我的代碼 - 我得到的錯誤「錯誤:預期 「)」錯誤隨機函數

這個錯誤出現becuse的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

我強烈建議使用'靜態const int的N = ...',而不是'#定義ñ...'爲數字常量。使用定義很容易導致難以理解的錯誤在您最不期望的位置。 – CygnusX1

+0

假設*「這個錯誤來自random_ints函數」*是準確的,'man 3 rand'告訴你使用'#include '。它看起來像你有正確的標題。看起來你在函數中有一個錯字。函數參數是***'N' ***,但是在循環中使用了***'M' ***。 – jww

回答

3

請考慮在解釋#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; 
}