Possible Duplicate:
Arrow operator (->) usage in C
I am trying to figure out the difference between the "." and "->" styles of data access in C language. Eg.
struct div{
int quo;
int rem;
};
1) Using "->"
struct div *d = malloc(sizeof(struct div));
d->quo = 8/3;
d->rem = 8%3;
printf("Answer:\n\t Quotient = %d\n\t Remainder = %d\n-----------\n",d->quo,d->rem);
2) Using "."
struct div d;
d.quo = 8/3;
d.rem = 8%3;
printf("Answer:\n\t Quotient = %d\n\t Remainder = %d\n-----------\n",d.quo,d.rem);
I am getting the same output for both the cases.
Answer: Quotient = 2 Remainder = 2
How these two approaches are working internally? And at what time which one should be used? I tried searching it on the internet but of not much help. Any relevant link is also appreciated.
Also is there any difference between their storage in memory?
Basic difference is this:
. is the member of a structure
-> is the member of a POINTED TO structure
So the .
is used when there is a direct access to a variable in the structure. But the ->
is used when you are accessing a variable of a structure through a pointer to that structure.
Say you have struct a
:
struct a{
int b;
}
However say c
is a pointer to a
then you know that: c = (*a)
. As a result ->
is being used as a alternative for a certain case of the .
. So instead of doing (*a).b
, you can do c->b
, which are the exact same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With