160 likes | 290 Views
Pointer to a Structure & Structure Containing a Pointer Difference Lesson xx. Objectives. Illustrate the difference between a pointer to structure and a structure that contains a pointer When to use the pointer to structure (-> ) operator When to use the dot (.) operator. Structure Setup.
E N D
Pointer to a Structure & Structure Containing a Pointer DifferenceLesson xx
Objectives • Illustrate the difference between a pointer to structure and a structure that contains a pointer • When to use the pointer to structure (-> ) operator • When to use the dot (.) operator
Structure Setup struct student { long id; int age; }; int main ( ) { student s; s.id = 25691; s.age= 17; student *ps = &s; return 0; } s (2fe) 25691 s.id 17 s.age
Pointer to a Structure struct student { long id; int age; }; int main ( ) { student s; s.id = 25691; s.age= 17; student *ps = &s; return 0; } 2fe ps s (2fe) 25691 s.id 17 s.age
Legal Expressions with a Pointer to a Structure 2fe s.id s.age ps-> id ps->age ps s (2fe) 25691 s.id 17 s.age
Illegal Expressions with a Pointer to a Structure 2fe s->id s->age ps. id ps.age ps s (2fe) 25691 s.id 17 s.age
Different Syntax with Pointer to a Structure 2fe s.id (*ps).id ps->id ps s (2fe) 25691 s.id 17 s.age
Incorrect Syntax with Pointer to a Structure //illegal syntax *ps.id *(ps.id) 2fe ps s (2fe) 25691 s.id //legal syntax (*ps).id 17 s.age
Structure Containing Pointers struct student { long *id; int *age; }; int main ( ) { student s; long i; int a; s.id = &i; s.age= &a; *s.id = = 25691; *s.age = 17; return 0; } s.id s (55d) s.age
Variable Declarations struct student { long *id; int *age; }; int main ( ) { student s; long i; int a; s.id = &i; s.age= &a; *s.id = = 25691; *s.age = 17; return 0; } s.id s (55d) s.age i (1ab) a (2fe)
Initializing a Structure That Contains Pointers struct student { long *id; int *age; }; int main ( ) { student s; long i; int a; s.id = &i; s.age= &a; *s.id = = 25691; *s.age = 17; return 0; } 1ab s.id s (55d) 2fe s.age i (1ab) a (2fe)
Indirection with Structure Containing Pointers struct student { long *id; int *age; }; int main ( ) { student s; long i; int a; s.id = &i; s.age= &a; *s.id = 25691; *s.age = 17; return 0; } 25691 1ab s.id 17 s (55d) 2fe s.age i (1ab) a (2fe)
Legal Expressions with Structure That Contains Pointers 25691 1ab s.id 17 s (55d) *s.id= 25691; *(s.id)= 25691; (*s.id) = 25691; *s.age = 17; 2fe s.age i (1ab) a (2fe)
Illegal Expressions with a Structure That Contains Pointers 25691 1ab s.id 17 s (55d) 2fe s.age (*s).id = 25691; s->id= 25691; i (1ab) a (2fe)
Comparison 25691 1ab ps is a pointer to the structure s. s.id 17 s (55d) 2fe 2fe ps s.age i (1ab) s (2fe) a (2fe) 25691 s.id 17 s.age s is a structure that contains 2 pointers
Summary • Illustrate the difference between a pointer to structure and a structure that contains a pointer • When to use the pointer to structure (-> ) operator • When to use the dot (.) operator