We covered C structures before, and in this lesson, we go through C pointers and structures. In C language, it is possible to define a structure type pointer, just like defining other types of pointers.
Defining structure pointers is the same as defining structure variables, except that the variable name is preceded by a *. Consider the following example:
struct bal{
float balance;
char name[80];
}person, *p;
The person is a structure variable, and p is a structure pointer. Now consider the following expression:
p = &person;
The address of the person structure is assigned to the p pointer.
To access the contents of the structure’s elements with a pointer, the pointer must be enclosed in parentheses. Pay attention to the following code:
(*p).balance;
In general, two methods could be used to access the structure’s elements pointed to by a pointer:
p -> balance;
Here it is necessary to state that arrays, pointers, and structures are closely related. Meanwhile, their related operators, including subscript or [ ], structure member or dot, and indirect access to structure member or ->, all have the highest precedence.
Indirect access or * and address extraction or & operators have second priority. If these appear together in an expression, the desired code should be written a little carefully. Pay attention to the following example:
struct point{
float x;
float y;
};
struct line{
struct point first;
struct point last;
char name
}a = {{1, 1},{10, 20}, 'a'};
struct line m[] = { { {2, 3}, {4, 5}, 'c'},
{ {4, 6}, {8, 1}, 'm'},
{ {8, 5}, {4, 2}, 'x'}};
struct line *pa = &a;
struct line *pm = &m[1];
It’s the time to access the structures’ members:
a.first.x
pa->first.x
(a.first).x
(pa->first).x
(*pa).first.x
The following two expressions also have the same meaning:
m[1].last.y
pm->last.y