[英]assigning a 2D array element to single pointer
我正在嘗試學習C。我是C編程的新手。 我有以下功能。
/*dA would be a pointer to a 2D array*/
void normalizeCols(float* dMu, float* dSigma, float* dB, float* dA, int n){
int col, row;
for(col=0; col < n; col++)
/*Step 1: calculating mean*/
float tempMu = 0.0;
dMu = &tempMu;
for (row=0; row < n; row++){
/*I am adding all the elements of the column*/
dMu += *(*(dA+row)+col); //ERROR: operand of * must be a pointer
}
/*dividing dMu by number of dimension(square matrix)*/
dMu /= (float) n; //ERROR: expression must have arithmetic or enum type
//More code here
}
}
我試圖找到一列的意思。 我得到了以上片段中已評論的兩個錯誤。 我該如何解決?
如果您知道矩陣是正方形的(即行長為n
,它也是行數),則只需手動進行尋址即可。
然后,內部循環變為:
/*Step 1: calculating mean*/
float tempMu = 0;
for (row=0; row < n; row++){
/*I am adding all the elements of the column*/
tempMu += dA[col * n + row];
}
/*dividing dMu by number of dimension(square matrix)*/
tempMu /= (float) n;
另外,將輸入參數const
使其更清楚,然后將int
切換為size_t
。
當然,請確保按正確的順序(行優先或列優先)進行訪問,否則將導致可怕的緩存崩潰。
(dA+row)
是一個指針,它從dA
移出row
距離,乘以dA
類型指向的大小。
*(dA+row)
給出指針(dA+row)
所指向的位置的值
*(dA+row)+col
將該值添加到col
*(*(dA+row)+col)
是非法的,因為您只能取消引用不是的指針。
您的tempMu
應該是:
tempMu += *(dA + row * n + col)
在這行上:
dMu += *(*(dA+row)+col); //ERROR: operand of * must be a pointer
請注意, dA
類型為float*
,因此*(dA+row)
是float
, col
被提升為float
以便添加到此值,該值現在位於最外面的括號中。 當用最左邊的*
取消引用時,您試圖取消引用float
,這是錯誤的根源。
為了使該行正確鍵入, dA
必須為float**
,但是您還有其他錯誤:例如,此處的dMu
是一個指針,您將使用+=
而不是一個值進行遞增。 您是說*dMu += ...
嗎?
不太清楚您想做什么。 從代碼中,我看到您正在嘗試使用指針進行一些“危險”的操作。
/I am adding all the elements of the column**/
dMu += *(*(dA+row)+col);
您沒有在列中添加所有元素,而是將dMU指針移到了另一個內存位置。
*dMU += dA[row][col]
....
*dMu /= (float) n;
它應該是正確的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.