Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "->" and "." in C [duplicate]

Tags:

c

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?

like image 748
Atul Gupta Avatar asked Dec 30 '12 00:12

Atul Gupta


1 Answers

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.

like image 115
Rivasa Avatar answered Sep 22 '22 07:09

Rivasa