[英]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.