Having some concerns about the functionality of the member reference and pointer operators..
Take the following example:
struct ID{
uint8_t index;
bool active;
}
struct Square{
struct ID shortID;
struct BUDDY *bud;
uint8_t x;
uint8_t y;
};
And then I later return a pointer to a square.. My question is: Can I then modify members of ID and have the changes reflected in the nested struct?
void function1()
{
Square *someSquare = GetSquare(1);
someSquare->shortID.index = 89; // Is this now reflected everywhere? OR was the shortID struct only modified in the scope of this funciton..
}
void function2()
{
Square *someSquare = GetSquare(1);
if ( someSquare->shortID.index != 89 )
{
// Dang...
}
}
Thanks!
EDIT:
Thanks for the concise answers, yes the GetSquare function returns a pointer to the specified index of an array of squares. Like so:
Square* GetSquare( uint8_t index )
{
return &squares[index];
}
So the instance should be the same every time, as the "squares" array is allocated once on object creation. So thank you for your insight my problem must be elsewhere in my code :)
yes because someSquare is a Square*
the ->
operator is like a (*varname).
.
So it is the content of the pointer and you get the type Square
.
Then you can just modify the variable with .
, because its a struct and all variables are public not like it could be in classes.
The Changes you made in function1 can be seen in function2 if the GetSquare
returns the same object that could be the case if your GetSquare
looks like this.
Square * GetSquare(int i)
{
static Square * pSquare = 0;
if (pSquare)
pSquare = malloc(sizeof(static Square));
return pSquare;
}
or for global variables like this
static Square pSquare ;
Square * GetSquare(int i)
{
return &pSquare;
}