2013-04-06 170 views
4
void load(int *n, double *x, double **arr, bool randomize) 
{ 
    *arr = (double*)malloc((*n + 1) * sizeof(double)); 
    srand(time(NULL)); 
    for(int i = 0; i <= *n; i++) 
    { 
     if(! randomize) 
     { 
      scanf("%lf", *arr + i); 
     } 
     else 
     { 
      *(arr + i) = rand(); 
     } 
    } 
} 

基於randomize參數,我想用隨機或自定義雙精度數來填充數組。但是,此代碼不能編譯,它在其他部分顯示"invalid conversion from int to double"無法將雙精度轉換爲雙精度

替換rand()與任何浮點值如5.0顯示「不能將double轉換爲double」。

(double) rand()(double) 5拋出類似的錯誤。

*n當然是在這個函數的前面讀到的,我只是把它剪掉了。

這裏有什麼問題?

回答

2

您引用的錯誤消息不完整。它在double之後缺少一個星號:*(arr + i)的類型是double*而不是double,並且不能將intdouble轉換爲double*

想必你的意思

 *(*arr + i) = rand(); 

 (*arr)[i] = rand(); 
+0

呃,學習C指針和引用是相當富他媽的難;-)謝謝! – user2251921 2013-04-06 15:58:27

+2

@ user2251921:不客氣。順便說一句,在C中的參考很容易 - 沒有任何! ;-) – NPE 2013-04-06 16:21:50

0

*(arr + i) = rand(); - >(*arr)[i] = rand();