0

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

4
  • 4
    You are going to have to clarify your question. Do you know what a pointer is? Jul 10, 2010 at 19:18
  • Pointer is not directly related to saving memory - it is simply an address of something (variable, beginning of memory block, "nothing" (zero or "NULL"), etc).
    – SigTerm
    Jul 10, 2010 at 19:23
  • 4
    i think this was asked a few hours ago, stackoverflow.com/questions/3219771/pointer-help-in-c-c
    – tjm
    Jul 10, 2010 at 19:23
  • 3
    Maybe the OP refers to the fact that passing a pointer is less costly than passing a copy of a larger data structure. Jul 10, 2010 at 19:24

1 Answer 1

5

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.