File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes C / C++ and the fly likes pointer's power outside the function Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Languages » C / C++
Bookmark "pointer Watch "pointer New topic

pointer's power outside the function

abhay jain
Ranch Hand

Joined: Jun 03, 2011
Posts: 130
"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

Joined: Oct 13, 2005
Posts: 46345
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

Joined: Mar 18, 2011
Posts: 312

Please move line number 24 to line number 2.

Not many get the right opportunity !
Brian Overland
Ranch Hand

Joined: Sep 09, 2011
Posts: 36
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
"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
I agree. Here's the link:
subject: pointer's power outside the function
It's not a secret anymore!