![]() |
|
#1
|
|||
|
|||
Pointer ProblemI'm sure this is really simple and stupid, but I'm not exactly sure what I am doing wrong. I have an array in an object. I would like to accept a pointer as an argument and set that pointer to the address of some index in that array for the calling class to use. Basically, the pointer is always equal to 0 when I try to use it. I probably posted more than necessary but it is very simple so here is a test example that exhibits the problem. The main and setptr functions should make it obvious what I am trying to do.
CPP / C++ / C Code:
The result is as follows: Initial: 0 Member: 0x3d3ca8 Argument: 0x3d3ca8 Set: 0 It is like it goes out of scope or something but I don't think it should. Any answers? Thanks |
|
#2
|
|||
|
|||
Re: Pointer ProblemQuote:
If you want a function that changes the value of one of its arguments (so that the change is reflected back into the calling program), there are a couple of ways: 1. Make the argument a pointer to the variable, then in the function de-reference the pointer to access the value of the variable (this works for C and C++). (So, if the variable is a pointer (int *arg), you would pass a pointer to the pointer (int **arg).) Syntax in the calling program changes to use the address of the pointer. Syntax in the function changes to dereference the pointer-to-pointer. 2. Make the argument a reference to the variable, then whatever you do in the function is actually acting on the original (this works for C++ only). (Otherwise the function only changes the value of its local copy of the argument, and this does not change the value of the corresponding variable in the calling program.) For C++, many people prefer the second one: CPP / C++ / C Code:
With these changes (and only these changes), I saw the following output: Code:
Regards, Dave |
Recent GIDBlog
NARMY by crystalattice
| Thread Tools | Search this Thread |
| Rate This Thread | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Pointer Usage in C++: Beginner to Advanced | varunhome | CPP / C++ Forum | 0 | 19-Aug-2005 09:25 |
| [Tutorial] Pointers in C (Part II) | Stack Overflow | C Programming Language | 0 | 27-Apr-2005 17:36 |
| Pointer Problem | nusstu | C Programming Language | 4 | 15-Apr-2005 11:31 |
| Please help! Newbie pointer problem! | robsmith | C Programming Language | 5 | 12-Mar-2005 04:48 |
| C Pointer problem | fwongmc | C Programming Language | 8 | 04-Dec-2004 12:34 |
Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The