structures and pointers
I'm not sure what I'm doing...
Let say I have a structure
struct Inner{
exampleType a;
int b;
}
struct Outer{
int current;
int total;
Inner reco开发者_如何学Pythonrds[MAXNUMBER];
}
struct Outer2{
Outer outer;
}
And I have the following functions:
void try3( Outer2& outer, type var, type2 var2 ){
}
void try2( Outer2* outer ){
try3(*outer, var, var2);
}
Inside main:
int myMain( int argc, char *argv[] ){
Outer2 outer2;
try2 (&outer2);
}
Here's the question. Can I increment the value of current by sticking the following line in try3:
++outer.outer.current;
errr, no, try3 has no knowledge of a thing caller outer2.
you can go outer.outer.current++; in try3
Sure you can, why not? Here is a working example for you:
typedef short exampleType;
struct Inner
{
exampleType a;
int b;
};
struct Outer
{
enum { MAXNUMBER = 2 };
int current;
int total;
Inner records[MAXNUMBER];
};
struct Outer2
{
Outer outer;
};
typedef int type;
typedef int type2;
void try3 (Outer2& outer, type var, type2 var2)
{
++outer.outer.current;
}
void try2 (Outer2* outer)
{
int var = 1, var2 = 2;
++outer->outer.current;
try3(*outer, var, var2);
}
int main ()
{
Outer2 outer2;
outer2.outer.current = 1986;
try2 (&outer2);
}
From try3
, you would need to use ++outer.outer.current
since outer
is the name of the variable at the point. To answer the actual question though, look at the two functions. try2
takes a pointer to an Outer2
, so no copy is made. try2
passes this to try3
which take a reference to an Outer2
, so again no copy is made. This means that yes, ++outer.outer.current
will in fact affect the original outer2
declared in myMain
.
Edit (per Brian's comment)
However, outer.outer.current
is never initialized, unless that's not your true myMain
, so the final value of current
is undefined since the value was never defined before the increment.
精彩评论