I want to know about the pointer in C and C++ - how does it help in saving memory? I searched but did not get a satisfactory answer. Please help me out.
If you compare the following two pieces of code:
foo() {
large_struct x;
bar(x);
}
bar(large_struct x) {
//do some funny things
}
and
foo() {
large_struct* x;
bar(x);
}
bar(large_struct* x) {
//do some funny things
}
In the first piece, the large struct x is copied in memory, while in the second snippet just a pointer is copied in memory. That are the points, when you can save memory with pointers.
Not sure exactly what you're after but ... storing a pointer takes less memory than storing an entire copy of the object it's pointing to.
In addition to what others have said, pointers are necessary for dynamic memory allocation (this also applys to higher level languages, but is (usually) abstracted away). This means that without pointers, you're limited to the (generally rather small) stack memory, which is more in need of conservation.
Pointers are basically used to Point a location in memory. The type of pointer refers to the type of memory it is pointing to (normally), e.g: a char * (character pointer points to a memory with characters in it), also this "type" of pointer has a lot to do with the pointer arithmetic, like e.g: how many bytes of jump the address will make if you add an integer to the pointer's name.
In C++ you can claim memory from the system on the run time by using new operator. This type of memory is known as Dynamic Memory and should be delete explicitly. The pointer notation is used to point to the such type of memory allocated by using "new" operator. e.g:
char * a = new char;
or
char * a = new char[10]
such a memory must be deleted or returned to the system using delete keyword e.g:
delete a;
or
delete [] a;
It was seen as a practice from our deer C++ programmers that they tend to forget deleting such claimed memory, hence Managed languages came into being. Most popular being Java, C# and managed C++ ( C++ CLI).
(It seems, I can write a full length article on what pointer are, but i tried being to the point to your question).
I hope you will be satisfied with my answer. I hope this helps