Just a question

Sorry if it's a stupid question, I'm not very good at C++.
But why are pointers useful? I have no idea what it's used for.
When you declare and use data, that data takes up space in memory.
Pointers are a useful tool to manipulate and organize this memory (and data) directly.
One such example is to manipulate a variable from within a function.
Here's an example. The function toZero is a function that takes a pointer to an integer and changes the contents of that memory to zero.
Remember, the address of something is equivalent to a pointer to that memory.
If you think of memory, or address, as a location, and pointers as a means to read and write to locations, then the concept will be very simple.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
void toZero(int*);
int main(int argc, char **argv)
{
	int number= 5;
	toZero(&number); //pass the address (a pointer to) of number.
	std::cout << number << std::endl;
	return 0;
}

void toZero(int *ptr)
{
	*ptr= 0; //dereference the pointer so the *contents* are manipulated and not the pointer itself.
}
Ah.. I see. Thank you for your help.
Topic archived. No new replies allowed.