Professional Documents
Culture Documents
STRUCTURES
By
Ms. P.JAYALAKSHMI, AP/CSE
Ms. K.RAMYA, AP/CSE
Programming Skills-C Programming
Structures
Structure Definition
Structure Declaration
Member Access
Memory Layout
Example
Array of structures
Nested structures
Functions and Structures
Structures
• structures are used to group together different types of
variables under the same name. For example you could
create a structure “telephone”:
• struct telephone
• {
• char *name;
• int number;
• };
• To access the members of the structure telephone, you
must use a dot between the structure name and the
variable name
Member Access
• Indirect access s->m: equivalent to (*s).m
– Dereference a pointer to a structure, then return
a member of that structure
– Dot operator has higher precedence than
indirection operator , so parentheses are needed
in (*s).m
(*fido.owner).name or fido.owner->name
id num_avail
cost
0 1 2 … 98 99
• An array of structs: Multiple types of data
in each array element.
0 1 2 … 98 99
Example
• We often use arrays of structures.
• Example:
StudentRecord Class[100];
strcpy(Class[98].Name, "Chan
Tai Man");
Class[98].Id = 12345;
strcpy(Class[98].Dept, "COMP");
Class[98].gender = 'M';
Class[0] = Class[98];
access
records
Chan Tai Man
12345 M
COMP
...
0 1 2 … 98 99
Example
struct line{
point p1, p2;
};
line L;
struct triangle{
point p1, p2, p3;
};
triangle T;
Sample Program With Structs
• Illustration
This program illustrates creating structs and then declaring
and using struct variables. Note that struct personal is an
included data type in struct "identity".
*/
#include <stdio.h>
struct personal //Create a struct but don’t reserve space.
{ long id;
float gpa;
};
struct identity //Create a second struct that includes the first one.
{ char name[30];
struct personal person;
};
Main program
int main ( )
{
struct identity js = {"Joe Smith"}, *ptr = &js ;
js.person.id = 123456789 ;
js.person.gpa = 3.4 ;
printf ("%s %ld %f\n", js.name, js.person.id,
js.person.gpa) ;
printf ("%s %ld %f\n", ptr->name, ptr->person.id,
ptr->person.gpa) ;
}
Function with a Structured Input/Output Argument
• For the following function, we have to call it
by
“scan_planet(¤t_planet);”
– The input argument is also used to store the result.
uses
• Uses of C structures:
• C Structures can be used to store huge data. Structures
act as a database.
• C Structures can be used to send data to the printer.
• C Structures can interact with keyboard and mouse to
store the data.
• C Structures can be used in drawing and floppy
formatting.
• C Structures can be used to clear output screen
contents.
• C Structures can be used to check computer’s memory
size etc.