View previous topic :: View next topic |
Author |
Message |
kWoody_uk
Joined: 29 Jan 2015 Posts: 47 Location: United Kingdom
|
How to correctly compare address of a structures |
Posted: Mon Feb 02, 2015 11:52 am |
|
|
Hi,
A bit basic, but could someone tell me the correct code to compare the addresses of a structure to a structure pointer?
I have tried the following and looked at the list code and it is being ignored:-
Code: |
typedef struct {
int8 a;
int8 b;
} structType;
structType structGlobal;
// Function prototype
void sumFunc( structType * structLocal );
// Main C entry point
void main( void )
{
structType structTest;
// Initialising elements of the local struct
structTest.a = 5;
structTest.b = 8;
// Initialising elements of the global struct
structGlobal.a = 2;
structGlobal.b = 4;
sumFunc( &structTest );
}
void sumFunc( structType * structLocal )
{
if ( &structLocal == &structGlobal ) {
// Rest of code
}
}
|
Is this just not legal C code or should I not be using the '&' symbol here?
Thanks in advance,
Keith |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19539
|
|
Posted: Mon Feb 02, 2015 1:03 pm |
|
|
A few too many &'s involved....
You are already passing the function, the address of a structure. This is what a 'pointer' is. The compiler optimises this away, since it knows this address, and it is not the same as &StructGlobal.
structLocal is already an address. You take the address of this, which then refers to the temporary variable used to pass the address. Not what you want.
Code: |
void sumFunc( structType * structLocal )
{
if ( structLocal == &structGlobal ) {
// Rest of code
}
}
|
One way to help avoid this type of mistake, is to always call 'pointers' with a name to remind you it is a poiinter. So something like _ptr. So:
Code: |
void sumFunc( structType * structLocal_ptr )
{
if ( structLocal_ptr == &structGlobal ) {
// Rest of code
}
}
|
|
|
|
kWoody_uk
Joined: 29 Jan 2015 Posts: 47 Location: United Kingdom
|
|
Posted: Tue Feb 03, 2015 3:12 am |
|
|
Thanks Ttelmah.
I'll take your advice regarding the naming of pointers too.
Best Regards,
Keith |
|
|
|