Structures
1
12/12/2022
Introduction
2
12/12/2022
Structure definitions
int roll_no;
char name[64];
float marks;
};
3
12/12/2022
Structures
int roll_no;
char name[64];
float marks;
};
4
12/12/2022
Declarations
int roll_no;
char name[64];
float marks;
}; /*this is structure definition */
struct student s1, s2[4], *ptr;
/*declaration of variables of type struct student */
5
12/12/2022
Declarations
int roll_no;
char name[64];
float marks;
} s1, s2[4], *ptr;
6
12/12/2022
Intialization
7
12/12/2022
Accessing members of a structure
int roll_no;
char name[64];
float marks;
}s1, s2[4], *ptr;
strcpy(s1.name, “Ram”);
s2[0].roll_no = 234123;
s2[0].marks = -1.0;
ptr = &s2[1];
ptr ->roll_no = 987654;
8
12/12/2022
Precedence
9
12/12/2022
Operations with structures
if (s1 == s2) { …. } /* not allowed */
10
12/12/2022
Nested structures
double x; double y;
};
struct rect {
struct point p1, p2;
};
struct rect screen;
screen.p1.x = 0.0; /* OK */
11
12/12/2022
Nested structures
double x;
struct nes p;
};
12
12/12/2022
Nested structures
double item;
struct list *next;
};
13
12/12/2022
Structures and functions
14
12/12/2022
Structures and functions
struct point makepoint(double, double);
int main( )
{
struct point s;
s = makepoint( 10 , 20.5);
}
struct point makepoint(double x, double y)
{
struct point temp;
temp.x = x; temp.y = y;
return temp;
}
15
12/12/2022
Structures and functions
{
p1.x += p2.x;
p1.y += p2.y;
return p1;
}
p = makepoint(0,10);
q = makepoint(100, 50);
x = addpoint(p, q); /* p, q are not modified by the function. Only values are passed. */
16
12/12/2022
p1, p2 are automatic local variables
Pointers to structures
17
12/12/2022
Pointers, structures and functions
double norm(struct point *p)
{
return( sqrt(p->x * p->x + p->y * p->y) );
}
18
12/12/2022
Arrays inside a structure
char name[64];
} y;
void func(struct x a)
{
strcpy( a.name, “hello”);
}
19
12/12/2022
typedef
Stud s1; /* s1 is variable of type struct student */
20
12/12/2022
Tag can be omitted
int roll_no;
char name[64];
float marks;
} Stud;
Stud s1, *ptr;
21
12/12/2022
typedef
typedef int Integer;
22
12/12/2022