Operator «arrow» pointer to member structure
Before reading this article, make sure you are familiar with structures and pointers
In English, this operator is called member selection operator
Let's start with some background:
Let's say we have a Website
Let this structure have three members name, year, rating
And we have a Website object called site1.
We can create a pointer to this object. Remember that:
The type of pointer should correspond to the type of object it points to.
So the syntax would be this:
struct Website * ptr;
So we set the right kind of pointer.
Now you can point to the desired object.
ptr = &heihei.ru
As usual. We've created a pointer and it points to the correct place.
But the structure has members: name, year, rating, so the question arises - how to address them ?
This problem is solved by ->.
We can write ptr->name, ptr->year, ptr->rating and everything is done.
#include <stdio.h>
struct Website {
char name[80];
int year;
float rating;
};
int main()
{
struct Website site1={"heihei.ru", 2018, 30.5};
struct Website *ptr;
By analogy with pointers such as char or int, we create
// pointer of type struct Website
ptr = &site1;
printf("%s %d %.1f\n", ptr->name, ptr->year, ptr->rating);
return 0;
}
gcc -o mso_example mso_example.c
./mso_example
heihei.ru 2018 30.5
Exercise
Replace the line
printf("%s %d %.1f\n", ptr->name, ptr->year, ptr->rating);
With
printf("%s %d %.1f\n", *ptr.name, *ptr.year, *ptr.rating);
Examine the error the compiler will produce and try to fix it.
The solution is just below
Solution
My compiler. GCC produces the following error
mso_example.c: In function ‘main’: mso_example.c:19:32: error: ‘ptr’ is a pointer; did you mean to use ‘->’? printf("%s %d %.1f\n", *ptr.name, *ptr.year, *ptr.rating); ^ -> mso_example.c:19:43: error: ‘ptr’ is a pointer; did you mean to use ‘->’? printf("%s %d %.1f\n", *ptr.name, *ptr.year, *ptr.rating); ^ -> mso_example.c:19:52: error: ‘ptr’ is a pointer; did you mean to use ‘->’? printf("%s %d %.1f\n", *ptr.name, *ptr.year, *ptr.rating); ^ ->
It tries to parse the dot between ptr and name and suggests using an arrow instead of the dot.
It doesn't see the * before ptr because the dot operator has higher priority than *
Enclose all *ptr in parentheses (*ptr)
printf("%s %d %.1f\n", (*ptr).name, (*ptr).year, (*ptr).rating);
Article author: Andrei Olegovich
| C development | |
| Textbook on C | |
| Boolean in C | |
| Sockets in C | |
| K&R | |
| What is argc, char * argv[] | |
| Function scanf() | |
| Pointers | |
| Structures in C | |
| Operator «arrow» pointer to member structure |