【问题标题】:assigning const array pointer to non const array pointer将 const 数组指针分配给非 const 数组指针
【发布时间】:2017-09-12 11:34:14
【问题描述】:
#include <iostream>

int main()
{
          const int l_loc[3] = {1,2,3};
          int (*l_loc2)[3] = NULL;
          l_loc2 = const_cast<int (*)[3]>(l_loc);   // complaining here. 
          std::cout<<l_loc2[1]<<std::endl;
                   return 0;
}

./example.cpp:7: error: invalid const_cast from type ‘const int*’ to type ‘int (*)[3]’

我只能修改那条尖线。请提供任何线索。

【问题讨论】:

  • @tobi303 UB 调情特技飞行?
  • @tobi303 - 可能是一个考试/面试问题
  • @StoryTeller 有一天我应该参加一次面试,只是为了看看面试官在我告诉他我拒绝从事类似工作时的表情。很高兴不是专业人士:P
  • @tobi303 - 令人钦佩。但值得庆幸的是,提出此类问题的公司越来越少。

标签: c++ pointers constants


【解决方案1】:
#include <iostream>

int main()
{
          const int l_loc[3] = {1,2,3};
          int (*l_loc2)[3] = NULL;
          l_loc2 = const_cast<int (*)[3]>(l_loc);   // complaining here. 
          std::cout<<l_loc2[1]<<std::endl;
                   return 0;
}

l_loc 是指向数组中第一个整数的指针。它包含的地址是不变的。您不能重新分配 l_loc 以指向另一个整数常量数组。这就是为什么您还必须投射l_loc 的地址。因此,您需要传递l_loc 的地址而不是l_loc2 = const_cast&lt;int (*)[3]&gt;(l_loc),即&amp;l_loc。结果l_loc2 = const_cast&lt;int (*)[3]&gt;(&amp;l_loc)希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2014-08-23
    • 1970-01-01
    • 2011-03-19
    • 1970-01-01
    • 2012-08-04
    • 2021-12-08
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多