简体   繁体   中英

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?

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)

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.

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 .

*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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM