Reputation: 41
I am new to the C programming language and I am trying to understand the intent of a function which takes a pointer argument but uses the address of operator on it as though it was a variable name in the function's body? The parameters being passed are of type struct. In other words, why did the author choose to use &lib -> fatfs; instead of lib->fatfs? Is the "address of" operator used to ensure that a null pointer is not being passed?
void SDCardLib_init(SDCardLib * lib, SDCardLib_Interface * interface)
{
lib->interface = interface;
f_mount(0, &lib->fatfs);
disk_initCallBack(interface);
}
Upvotes: 1
Views: 72
Reputation: 60068
&lib->fatfs
is the same as &(lib->fatfs)
or &((*lib).fatfs)
. The &
doesn't take the address of the pointer named lib
.
&lib->fatfs
is essentially whatever lib
points at plus whatever offset the fatfs
member is at.
The following piece of code asserts that:
//imagine a fake SDCardLib
typedef long sometype;
typedef struct {
int something0;
sometype fatfs;
int something1;
} SDCardLib;
#undef NDEBUG //make sure asserts are kept
#include <assert.h>
#include <stddef.h> //offsetof
#include <stdlib.h> //malloc
int main()
{
SDCardLib *lib = malloc(sizeof *lib);
if(!lib) return 1;
assert( &lib->fatfs ==
(sometype*) ((char*)lib + offsetof(SDCardLib,fatfs)) );
assert( &lib->fatfs == &(lib->fatfs) );
assert( &lib->fatfs == &((*lib).fatfs) );
}
Upvotes: 4
Reputation: 223917
The address-of operator is not being applied to the pointer lib
but to the fatfs
member of the pointed to object. The ->
operator has higher precedence then the unary &
operator.
That means that &lib->fatfs
is the same as &(lib->fatfs)
. This should make it more clear what &
is taking the address of.
Upvotes: 5