c++ - 在 C++ 中相互引用 bool 指针的正确方法

标签 c++ pointers

我一直在寻找解决这个小 bool 指针引用问题的方法,但找不到解决方案。我知道 C++ 在使用指针和引用时会变得复杂。

下面的代码片段使用类似 bool* 引用的流程,我想将 temp5 值(即 true)分配给 bool* 一直到 temp并打印出来。然而,这最终会导致段错误。想知道在这种情况下出了什么问题,或者我对指针和引用缺少什么。谢谢!

#include <iostream>

int main()
{
  bool* temp= nullptr;
  bool* temp2;
  bool* temp3;

  temp2 = temp;
  temp3=temp2;

  bool temp5 = true;
  *temp3 = temp5;

  std::cout << *temp <<std::endl;

  return 0;
} 

最佳答案

您的 temp3 未初始化。取消引用它可能会导致访问冲突。并且 tempnullptr,取消引用它(特别是 - 通过指针分配)也是被禁止的。换句话说,您有很多指示,但所有指示都没有指向任何地方。

此外,尚不清楚这段代码实际应该做什么。 你想要这样的东西吗?

int main()
{
  bool value = false;

  bool* temp= &value;
  bool* temp2;
  bool* temp3;

  temp2 = temp;
  temp3=temp2;

  bool temp5 = true;
  *temp3 = temp5;

  std::cout << *temp <<std::endl;

  return 0;
}

关于c++ - 在 C++ 中相互引用 bool 指针的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39921047/

相关文章:

C++ 错误 : invalid conversion from ‘char’ to ‘const char*’ [-fpermissive]

c++ - 具有 std::atomic 成员变量的类的复制构造函数/赋值运算符出错

c++ - 如何在 wxWidgets 的同一窗口中拖放文件和文本?

c++ - 检查指针是否为 NULL 并导致运行时错误

c - signal() 函数返回的函数指针的用途是什么?

c - 指针值不一起改变?

c++ - 匹配号码

c++ - 使用 boost::regex 的正则表达式问题

C - 这个变量的类型是什么?

c - C中数组指针的奇怪行为