将2D数组元素分配给单个指针

时间:2014-03-10 15:36:19

标签: c pointers

我正在努力学习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
       }
}

我试图找到一个列的意思。我在上面的代码片段中得到了这两个错误。我该如何解决这个问题?

4 个答案:

答案 0 :(得分:1)

如果您知道矩阵是方形的(即行长度为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

当然,请确保以正确的顺序(行主要或列主要)进行访问,否则您将遇到可怕的缓存抖动。

答案 1 :(得分:1)

(dA+row)是一个指针,从dA移动row倍于dA类型的距离。

*(dA+row)给出(dA+row)指针所指位置的值

*(dA+row)+col将该值添加到col

*(*(dA+row)+col)是非法的,因为你只能取消引用不是的指针。

您的tempMu应该是:

tempMu += *(dA + row * n + col)

答案 2 :(得分:1)

在这一行:

dMu += *(*(dA+row)+col); //ERROR: operand of * must be a pointer

请注意,dA的类型为float*,因此*(dA+row)floatcol会提升为float才能成为*添加到此值,现在位于最外面的括号中。如果您取消引用最左侧的float,则会尝试取消引用dA,这是您错误的来源。

为了使该行的类型正确,float**必须为dMu,但您还有其他错误:+=此处,例如,是指针,您可以正在以*dMu += ...递增,而不是值。您的意思是{{1}}吗?

答案 3 :(得分:0)

不太清楚你想做什么。从代码我看到你正试图用指针做一些“危险”的操作。

            /I am adding all the elements of the column**/
            dMu += *(*(dA+row)+col);

您没有添加列中的所有元素,但是您正在将dMU指针移动到另一个内存位置。

*dMU += dA[row][col]
....
*dMu /= (float) n;

它应该是正确的。