invalid conversion from ‘const int*’ to ‘int*’

前端 未结 1 2067
囚心锁ツ
囚心锁ツ 2021-01-23 09:51

I receive the following error

$ g++ test.cpp
test.cpp: In function ‘int test1(const int**, int)’:
test.cpp:11:14: error: invalid conversion from ‘const int*’ to          


        
相关标签:
1条回答
  • Just write

    int const *a;  // or const int *a; which is the same.
    

    ...then const correctness will be preserved. The compiler complains because you try to assign v[i], which is an int const *, to int *, through which the elements that v promised would not be changed could be changed. Since you don't attempt to do that later, just use an int const* to reassure the compiler.

    Note that a will remain a pointer variable (so you will be able to reassign it), only it will point to integer constants (which you cannot then change through a). To declare a constant pointer, you would write

    int       *const a; // pointer constant to int variable,or
    int const *const a; // pointer constant to int constant
    

    The other error is similar in origin, although it is a bit more difficult to see why it is forbidden (since you're only adding const and don't try to take it away). Consider: Were an assignment from int** to int const ** allowed, you could write the following piece of code:

    int const data[] = { 1, 2, 3, 4 }; // this is not supposed to be changed.
    
    int *space;
    int **p = &space;
    int const **p2 = p; // this is not allowed. Were it allowed, then:
    
    *p2 = data;
    **p = 2;     // this would write to data.
    

    And that would be bad, mkay. If you instead write

    int test1(const int *const *v, int num)
    

    Now v is a pointer (variable) to pointer constant(s) to int constant(s). Since *v is then constant, the loophole is closed, and the compiler will accept it.

    0 讨论(0)
提交回复
热议问题