Isura Nirmal Isura Nirmal - 2 months ago 6
C++ Question

Correct way to reference Boolean pointers each other in C++

I was looking for way to solve this small Boolean pointer references problem but cannot came to a solution. I know C++ becomes complex when it comes to usage of Pointers and references.

Below code fragments uses a flow like references of

bool*
and I want to assign the temp5 value (which is
true
) to the bool* all the way to temp and print it. However this ends up with segmentation fault. Would like to know what has gone wrong or what am I missing about pointers and references when in a situation like this. Thank You!

#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;
}

Answer

You are assigning value to a nullptr. That is what is causing segmentation fault

Just replace line

bool* temp = nullptr;

with this

bool* temp= new bool;

It will work now.

And don't forger to delete it with delete operator.