Quick question about pointers

Can a pointer point to variables in adifferent function or back to the main body of the code? If not, what a pointers actually used for?
Last edited on
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.

Examples:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#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 = new char[16]; // Created on the heap - will not be destroyed upon going out of scope
	strcpy(str, "Hello World");
	return str;
}
and for the record, don't use char*s when there are std::strings, are you a C programmer BranFlakes?
Last edited on
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.
point taken but beginner programmers will imitate code they're shown, and as such we should only show them code that we would advise using ourselves
Hahah i try to understand the code and then try to use it in other places so no worries there, thanks for the help.
Topic archived. No new replies allowed.