谁能帮我弄清楚为什么我的lValue总是出错

时间:2018-11-15 22:07:48

标签: c++

任何人都可以帮助我弄清楚为什么我的最内层循环器中不断出现错误吗?*突出显示它必须是可修改的lValue。

using namespace std;
#include <iostream>


int main()
{


    //Part I 
     int DIM1 = 200; 
     int DIM2 = 400;
     int DIM3 = 200; 

     const int DIMM1 = 200;
     const int DIMM2 = 400;
     const int DIMM3 = 200;


     myTimer st;


    st.start();
    int a[DIMM1][DIMM2][DIMM3];
    for (int i = 0; i < DIM1; i++) {
        for (int j = 0; j < DIM2; j++) {
            for (int k = 0; k < DIM3; k++) {
                a[i][j][k] = i + j + k;
            }
        }
    }
    st.stop();
    st.time();
    cout << time << endl;


    st.start();
    //int *a;
    int * a = new int[DIM1*DIM2*DIM3];
    for (int i = 0; i < DIM1; i++)
        for (int j = 0; j < DIM2; j++)
            for (int k = 0; k < DIM3; k++)
                *(a + (i*DIM2*DIM3) + 
                    j * DIM3 + k) = i + j + k;

    st.stop();
    st.time();
    cout << time << endl;



    st.start();
    int a[DIMM1][DIMM2][DIMM3];
    for (int k = 0; k < DIM3; k++)
        for (int j = 0; j < DIM2; j++)
            for (int i = 0; i < DIM1; i++)
                a[i][j][k] = i + j + k;
    st.stop();
    st.time();
    cout << time << endl;


    st.start();
    //int *a;
    int * a = new int[DIM1*DIM2*DIM3];
    for (int k = 0; k < DIM3; k++)
        for (int j = 0; j < DIM2; j++)
            for (int i = 0; i < DIM1; i++)
                *(a + (i*DIM2*DIM3) +
                    j * DIM3 + k) = i + j + k;
    st.stop();
    st.time();
    cout << time << endl;



    return 0;
}

错误是:

Severity  Code    Description Project File    Line    Suppression State
Error   C2372   'a': redefinition; different types of indirection
Error   C3863   array type 'int [400][200]' is not assignable
Error   C2086   'int a[200][400][200]': redefinition
Error   C2372   'a': redefinition; different types of indirection   
Error   C3863   array type 'int [400][200]' is not assignable
Error (active)  E0137   expression must be a modifiable lvalue  

1 个答案:

答案 0 :(得分:3)

查看c ++编译器错误时,您需要先查看第一个。其他的很可能是第一个引起的。

在这种情况下,您要在同一作用域中声明许多名为a的变量。重新声明a时,编译器会引发错误:

'a': redefinition; different types of indirection

然后它忽略此声明,并尝试继续编译文件的其余部分,由于变量类型不是您期望的那样,这将导致后续错误(编译器正在处理此文件中a的所有实例)作为数组)。

您需要为每个变量使用不同的名称,或者将变量包含在单独的范围中。例如,以下任一有效:

int a;
// do stuff with a
int b[10];
// do stuff with b

或:

{
    int a;
    // do stuff with a
}
// int a no longer exists
{
    int a[10];
    // do stuff with a
}