The .
member selection operator requires that its left operand have a struct
or union
type. The expression p2
has type struct product
, so it's a valid operand for the .
operator. The expression p3
has type struct product *
(pointer to struct product
), so it is not a valid operand for the .
operator.
The ->
member selection operator requires that its left operand have a pointer to struct
or union
type. The expression p3
has type struct product *
, so it's a valid operand for the ->
operator. The ->
performs an implicit deference of the pointer - a->b
is equivalent to writing (*a).b
.
The expression p2
is not a pointer - it does not have pointer type, so it is not a valid operand for the ->
operator. p2
doesn't point to anything, it is the thing.
Here's a bit of code I wrote to illustrate the difference between p2
and p3
- dumper
is a little utility I wrote to dump the contents of objects in memory:
#include <stdio.h>
#include "dumper.h"
#include <stdint.h>
int main( void )
{
struct product
{
double price;
int quantity;
char name[1];
};
struct product p2 = {1.00, 1, .name[0] = 'A'};
struct product *p3 = &p2;
char *names[] = {"p2", "p3"};
void *addrs[] = {&p2, &p3};
size_t sizes[] = { sizeof p2, sizeof p3};
dumper( names, addrs, sizes, 2, stdout );
return 0;
}
Here's the output:
Item Address 00 01 02 03
---- ------- -- -- -- --
p2 0x7ffeec515a68 00 00 00 00 ....
0x7ffeec515a6c 00 00 f0 3f ...?
0x7ffeec515a70 01 00 00 00 ....
0x7ffeec515a74 41 00 00 00 A...
p3 0x7ffeec515a60 68 5a 51 ec hZQ.
0x7ffeec515a64 fe 7f 00 00 ....
The struct
object p2
lives at address 0x7ffeec515a68
and contains a double
object (0x3ff0000000000000
, which is the binary representation of the floating point value 1.0
, starting at address 0x7ffeec515a68
), followed by an int
object (0x00000001
, starting at address 0x7ffeec515a70
) followed by a single char
object (0x41
, which is the character code for 'A'
, starting at address 0x7ffeec515a74
).
The pointer object p3
lives at address 0x7ffeec515a60
and contains the address of p2
(0x7ffeec515a68
).