If I pass a pointer to a function as an argument and assign to the pointer inside the function, shouldn't that be reflected in the calling scope?
In the following code, s==nullptr gets printed. Why did assignment to s inside the function assign_string not reflected in the main function?
#include<iostream>
#include<string>
void assign_string(std::string* s)
{
s = new std::string("Reassigned");
}
int main()
{
std::string* s = nullptr;
assign_string(s);
if (s == nullptr)
{
std::cout << "s==nullptr" << std::endl;
}
else
{
std::cout << "s!=nullptr" << std::endl;
}
return 0;
}
PS: I'm new to C++ and I might be using terms like "assign" loosely.
EDIT. Is passing pointer argument, pass by value in C++? has many useful answers.