代码之家  ›  专栏  ›  技术社区  ›  petersohn

'从某个类型**到常量某个类型**的转换无效'

  •  8
  • petersohn  · 技术社区  · 14 年前

    我有一个函数需要 const some_type** some_type 是结构,函数需要指向此类型数组的指针)。我声明了一个类型为 some_type* f(&some_array) 编译器(gcc)说:

    error: invalid conversion from ‘some_type**’ to ‘const some_type**’
    

    有什么问题吗?为什么我不能把一个变量转换成常量?

    3 回复  |  直到 14 年前
        1
  •  12
  •   jamesdlin    14 年前
        2
  •  1
  •   Matthew T. Staebler    14 年前

    你可以用一个中间变量。

    some_type const* const_some_array = some_array;
    f(&const_some_array);
    

    f .

    void f(some_type const* const* some_array);
    
        3
  •  1
  •   fret    14 年前

    也可以尝试使变量常量:

    some_type const *some_array = ....;
    

    这读作“some\ u array是指向const some\ u类型的指针”。代码无法修改所指向的对象。因此,必须先声明变量const,然后再将其传递给函数。

    (已编辑…)