yupe
yupe

Reputation: 127

what's the difference between the two statements?

I wrote the following code, there is some difference exist but I can't figure it out.

typedef struct {
    char* ch;   
    int length;
}Hstring;
int Strlength(Hstring* s) {
    return s->length; // if I use s.length there, error occurs.
}
int Strlength(Hstring s) {
    return s.length; // if I use s->length there, error occurs.
}

So what the differences between the two types? Will I get the same result? and why those errors occur?

Upvotes: 0

Views: 130

Answers (4)

Gerd
Gerd

Reputation: 2803

As already mentioned, the . operator is for accessing members of a struct, whereas the -> operator is for accessing members of a struct pointer.

However, another important difference between your two functions is that in Strlength(Hstring* s) the parameter is passed by reference, implying that the function operates on the "original" memory location of the data structure and therefore can modify its contents.

In contrast, in Strlength(Hstring s) the parameter is passed by value, implying that the function operates on a copy of the original structure and changes made within the function will not be visible outside the function.

See also this answer.

Upvotes: 1

kiran Biradar
kiran Biradar

Reputation: 12732

The difference is dot (.) and arrow (->) operators.

You can only use the dot (.) operator with a structure or union variable to access its members.

You can only use the arrow (->) operator with a pointer variable to access members of the structure or union the pointer points to.

Upvotes: 2

Edd Inglis
Edd Inglis

Reputation: 1105

To add to the previous answers that state that dot (.) is for 'normal' variables and arrow (->) is for pointers, note that arrow is a syntactic equivalent to a pointer de-reference followed by a dot, provided for convenience (since it's such a common operation).

Hstring* s;
s->length;   // this is equivalent to...
(*s).length; // ...this

The parentheses are needed since dot has a higher precedence than star. Without them, you'd be a) using a dot with a pointer and b) trying to de-reference the integer length field, both of which would be invalid.

Hstring* s;
*s.length;   // this is equivalent to...
*(s.length); // ...this (not what you want at all)

Upvotes: 3

lenik
lenik

Reputation: 23508

*s is a pointer, you may reference the members using operator ->, if there's no *, it's just a variable, you may reference the members using operator (dot) .

Upvotes: 0

Related Questions