tags:

views:

90

answers:

1

how does pointer in C++ helps in saving memory?

+3  A: 

Usually "pointer" and "saving memory" are used in the discussion of pass-by-reference and pass-by-value. Passing a value can be metaphorically described as handing an object back and forth, like say a table. Every time you return a table object or pass a table object, the system has to make an exact copy of the table for the other function to use. That copy takes up more room, hence "more memory".

table t;
function( t );
t = maketable();

In the above, t is copied before being passed to function(), and maketable creates a table within, only to make a copy and hand it back to be stored in t.

Passing by reference is akin to passing directions to the table around, say a piece of paper that says "the table in the corner of my room". When functions pass references/pointers around, it only needs to copy something small, hence "saving memory". The other function can then access "the table at" "the corner of my room". That's the literal english translation. For example:

table some_table;
table* paper_containing_address = &some_table;
function( paper_containing_address );
paper_containing_address = maketable();

In the above, there exists "some_table". Then "address of" (&) "some_table", i.e. ("the one at the corner of my room") is put into paper_containing_address. Then, only the paper needs to be passed to function, not a whole copy of a table. Likewise, maketable() presumably creates a table, and returns just its location, rather than having to make a copy of the whole table.

Hope this helps.

eruciform