Can a pointer point to variables in adifferent function
Yes, as long as the variables in that function are created on the heap instead of the stack or have not gone out of scope. Pointers can point to anywhere in the program's addressable space.
#include <iostream>
char* getBadString(); // Returns a locally defined string
char* getGoodString(); // Returns a string allocated on the heap
int main()
{
std::cout << getBadString() << std::endl; // Prints out garbage - it points to memory that has been cleared off the stack
char* str = getGoodString();
std::cout << str << std::endl; // Prints out "Hello World"
delete[] str;
std::cin.get();
return 0;
}
char* getBadString()
{
char str[16]; // Will be destroyed when the function returns
strcpy(str, "Hello World");
return str;
}
char* getGoodString()
{
char* str = newchar[16]; // Created on the heap - will not be destroyed upon going out of scope
strcpy(str, "Hello World");
return str;
}
Does it really matter for the purpose of explaining how to use pointers? Obviously it's advisable to use std::string in lieu of a raw pointer, but this was merely an example.