Pass by value

Jun 4, 2008 at 2:24pm
Hie , can someone explain how does pointers consisting pass by value works ? Thanks guys..
Jun 4, 2008 at 2:45pm
A pointer is a variable just like any other: It has a value.

Of course, the meaning of its value is different than, say, an int or a float, but it is still a discrete collection of bits stored in memory somewhere.

The stuff it actually points to is stored somewhere else. Hence, the pointer is said to contain the address of the data to which it points.

So, if you pass a pointer by value, you are passing its value (which is an address) to another pointer variable. And the other pointer variable can do whatever it wants with the stuff it points to...
1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
  {
  char* s = "Hello world!";

  print( s );  // (1)
  }

void print( char* p )  // (2)
  {
  for (; *p != '\0'; p++) // (3)
    cout << *p;
  cout << endl;
  }

So, the line marked (1) passes the value of s to the print() function.

On line (2), the variable p gets that same value. So now both s and p point to the same spot in memory.

On line (3), we modify p to point to a different part of memory, but since s and p are different variables the value of s (the address stored in s) never changes.

In either case, we have write access rights to whatever s/p/whatever points to. If you want to protect the data addressed by s, you'll need to declare p as

void print( const char* p )

which says "p is a pointer to an immutable array of char".

If you don't care if the array is changed, but you don't want the value of p to change, declare as:

void print( char* const p )

which says "p is an immutable pointer to an array of char", and line (3) would fail since p++ is now invalid.

Hope this helps.

Hope this helps.
Last edited on Jun 4, 2008 at 2:46pm
Topic archived. No new replies allowed.