首页 > 解决方案 > 为什么我在 C 中使用 Q++ 调用 Q[j] 数组索引后不起作用?

问题描述

这是一行小问题。

我有这个不能正常工作的代码行,因为我以前用过Q++

如果你看这段代码

Q[j] += *Q * *Q; //  Power^2 -> Sum to the top row at column index j

这会检测到 **** 堆栈粉碎 ** : 终止错误。

为什么?是因为我以前用过Q++吗?所以如果我打Q++了两次电话,那么当我打电话时Q[0],我真的在打电话Q[2]吗?

当我打电话时Q[j],我想将值放在row 0j,它介于0和之间Pcolumn。我怎样才能做到这一点?

暗示:

如果您替换此代码:

Q[j] += *Q * *Q; //  Power^2 -> Sum to the top row at column index j

 *Q = *Q * *Q; //  Power^2 

和 MATLAB 一样:Q = power(P-repmat(Q, 1, size(P, 2)), 2)

如何重复这个问题:

#include <stdio.h>
#include <stdint.h>

#define Pcolumns 10
#define Prows 3

// Repeat, substract, power and then sum
// MATLAB:
// Q = sum(power(P-repmat(Q, 1, size(P, 2)), 2), 1);
static void repmat_substract_power_sum(float Q[], const float P[]){
    // First row of Repeat -> Substract ->Power^2 -> Sum
    float q = *Q; // First column and first row value
    for(uint16_t j = 0; j < Pcolumns; j++){
        *Q = *P - q; // Substract
        *Q = *Q * *Q; // Power^2
        Q++;
        P++;
    }



    // The rest of the rows of Repeat -> Substract -> Power^2 -> Sum
    for(uint16_t i = 1; i < Prows; i++){
        q = *Q; // First column value at row i
        for(uint16_t j = 0; j < Pcolumns; j++){
            *Q = *P - q; // Substract
            Q[j] += *Q * *Q; //  Power^2 -> Sum to the top row at column index j
            Q++;
            P++;
        }
    }


}

int main()
{

    const float P[Prows*Pcolumns] = {-0.030123,  -0.163077,   0.218500,  -0.926896,  -0.159914,   2.344850,   0.473091,   0.039504,   0.590130,  -1.100642,
                                     -0.544295,   1.425373,  -0.337698,   1.440593,  -0.991939,  -0.457879,   0.136217,   0.173020,   0.947561,   0.596546,
                                     -0.145652,  -0.040126,  -0.835043,  -0.774521,  -0.333765,   1.586474, -1.811476,  -0.703679,  -1.382814,   0.406454};

    float Q[Prows*Pcolumns];
    Q[0] = 43;
    Q[Pcolumns*1] = -13;
    Q[Pcolumns*2] = 0.34;

    // Expected output on first row of Q: 2007.0   2071.3   1992.0   2139.3   2007.4   1811.7   1985.7   2020.2   1996.1   2129.7

    repmat_substract_power_sum(Q, P);


    for(int i = 0; i < Prows; i++){
        for(int j = 0; j < Pcolumns; j++){
            printf("%f\t", Q[Pcolumns*i + j]);
        }
        printf("\n");
    }

    return 0;
}

标签: arrayscindexing

解决方案


推荐阅读