• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

pointer's power outside the function

 
abhay jain
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Pointers enable us to access a variable that is defined outside the function."


i want to implement this above feature in this following simple code


/*

error: undefined symbol h
*/
 
Campbell Ritchie
Sheriff
Pie
Posts: 50189
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please indent your code.
That is really stylish, and easy to understand: *ptr= *ptr+=2;, isn't it?

Pointer arithmetic is hard enough at the best of times without your obscuring the logic with uninterpretable and incorrectly-spaced code.
The error you are quoting has nothing to do with pointers. It has to do with h not being in scope.
 
Madhan Sundararajan Devaki
Ranch Hand
Posts: 312
Java MS IE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please move line number 24 to line number 2.
 
Brian Overland
author
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First off, yes, moving line 24 to line 2 would make the code compile because it would make the variable h a global variable.

But to address the original question more specifically, let me state that one variable can access a variable in another function WHEN YOU PASS THE ADDRESS BETWEEN FUNCTIONS. There are plenty of examples of this in Chapter 6 of my book I believe.

For example, I have a value, i, set to 10, stored in variable i in one furnction. By passing the address of i (notated as &i) to function #2, I give function #2 access to the original variable, i... That is, furnction #2 can actually make permanent changes to the value of i...

void funct1() {
int i = 10;

"value of i before call is " << i << endl; // prints 10
funct2(&i);
"value of i after call is " << i << endl; // prints 20
}

void funct2(int *n) {
*n = *n * 2; // Double the value
}

Note that this does not work if you pass i directly, because argument values passed to a function are just thrown away. But function 2 uses a pointer to gain access to the original copy of i rather than just working on its own copy.

This is explained in much much greater depth in my books.

Brian Overland
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic