0% found this document useful (0 votes)
4 views31 pages

Structure

The document provides an overview of structures in the C programming language, detailing variable and data types, including system-defined and user-defined types. It explains how to declare, initialize, and manipulate structures, as well as the importance of passing structures as parameters and using pointers. Additionally, it covers nested structures, arrays within structures, and methods for representing tabular data using arrays of structures.

Uploaded by

10423049
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views31 pages

Structure

The document provides an overview of structures in the C programming language, detailing variable and data types, including system-defined and user-defined types. It explains how to declare, initialize, and manipulate structures, as well as the importance of passing structures as parameters and using pointers. Additionally, it covers nested structures, arrays within structures, and methods for representing tabular data using arrays of structures.

Uploaded by

10423049
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Structure in C language

Variable and Data Types

int x = 9;
• In programming we need something for holding data, and variable is the way
to do that.
• A data type in a programming language is a set of data with
predefined values. Examples of data types are: integer, float, string,…
• There are two kind of data types in programming languages:
• System-defined data types (also called Primitive data types)
• User-defined data types
System-defined data types
• The data types are defined by languages
• The number of bits are allocated to each data type is fully depend on
the language and compiler
• For example: in C language:
• int: 2 bytes (actual value depends on compiler)
• float: 4 bytes
•…
User-defined data types
• The user-defined data types are defined by the user himself.
• In C we can create structure. In C++/Java, we can create class.
• For example:
struct student{
char[20] name;
int id;
};
struct student x;
Data structure
• Data structure is a particular way of storing and organizing data in a
computer so that it can be used efficiently.
• General data structure: Array, Linked List, Queue, Stack,…
• Data structure is divided into two types:
• Linear data structure
• Non-linear data structure
Type Definition
• Syntax: typedef type Name ;
• Name becomes a name you can use for the type
• Examples: typedef struct {
typedef struct student Student; char[20] name;
Student x; /* x is an struct student */ int id;
Student* PtrToStudent } Student;
typedef char *STRING;
STRING sarray[10];
/* sarray is an array of char *’s, equivalent to declaring:
char *sarray[10]; */
Structured Variables
• Group of related values (but unlike array, where the values are not necessarily of
the same type)
• Each part of structure is a field, with an associated value
• The group is treated as a single unit (a single variable with parts)

VariableName
Field1 Field2 Field3 Field4
Structured Variable

• Declaration • Variable consists of parts


struct {
corresponding to the fields
Type1 FieldName1; • Memory set aside corresponding
Type2 FieldName2; to the total size of the parts
Type3 FieldName3; • Each part is an individual
/* as needed */ variable of the appropriate type
} VarName;
Structure Types
Tag declaration: Type definition:
struct TagName { typedef struct {
Type1 Field1; Type1 Field1;
Type2 Field2; Type2 Field2;
Type3 Field3; Type3 Field3;
/* any more */ /* any more */
}; } TypeName;
Variable declaration: Variable declaration:
struct TagName VarN; TypeName VarN;
Field Selection
• Dot (.) form to refer to field of • Example:
structured var
typedef struct {
• Syntax: VarName.FieldName int month, day, year;
} DATE;
• Each field treated as an
individual variable of that type void main() {
DATE d1;

d1.month = 12;
d1 d1.day = 2;
d1.year = 1970;
month day year
}
12 2 1970
Structure Initialization
• Can initialize structured variable by giving value for each field (in the
order fields are declared)
• Syntax:
STYPE Svar = { FVal1, FVal2, FVal3, … };
• Example:
typedef struct { d1
int month, day, year;
month day year
} DATE;
12 2 1970
DATE d1 = { 12, 2, 1970 };
Structure Assignment
• Can assign value of one structured var to another
• variables must be of same type (same name)
• values are copied one at a time from field to corresponding field
• Example:
d1
typedef struct {
int month, day, year; month day year
} DATE; 12 2 1970

DATE d1 = { 12, 2, 1970 };


DATE d2; d2
month day year
d2 = d1; /* Assignment */
12 2 1970
Structure Comparison
• Should not use == or != to compare structured variables
• compares byte by byte
• structured variable may include unused (garbage) bytes that are not equal
(even if the rest is equal)
• unused bytes are referred to as slack bytes
• to compare two structured variables, should compare each of the fields of the
structure one at a time
Slack Bytes
• Many compilers require vars to start on even numbered (or divisible by 4)
boundaries, unused bytes called slack bytes
• Example:
typedef struct { MyType v1;
char ch; MyType v2;
int num;
} MyType;
v1 v2
ch num ch num
2048
2049
2050
2051
2052
2053
2054
2056

2060
2061
2062
2063
2064
2065
2066
2067
Structure Example
#include <stdio.h>
printf(”Enter:\n”);
typedef struct { printf(" ID#: ");
int id; scanf("%d",&s1.id);
float gpa; printf(" GPA: ");
scanf("%f",&s1.gpa);
char class;
printf(" Class: ");
} Student;
scanf(" %c",&s1.class);
void main() {
Student s1; printf(”S#%d (%c) gpa =
%.3f\n",s1.id,s1.class,s1
s1 .gpa);
id gpa class }
Passing Structures as Parameters
• A field of a structure may be passed as a parameter (of the type of
that field)
• An advantage of structures is that the group of values may be passed
as a single structure parameter (rather than passing individual vars)
• Structures can be used as
• value parameter: fields copied (as in assignment stmt)
• reference parameter: address of structure passed
• return value (resulting structure used in statement) -- not all versions of C
allow structured return value
• best to use type-defined structures
Structure as Value Parameter
#include <stdio.h> void printS(Student s) {
/* Struc. Param. named s
typedef struct { created, fields of arg
int id; (s1) copied to s */
printf("S#%d (%c) gpa =
float gpa; %.3f\n",s.id,s.class,s.gpa);
char class; }

} Student; void main() {


Student s1;
s1
id gpa class s1 = readS();
printS(s1);
}
Structure as Return Value
typedef struct { Student readS() {
int id; Student s; /* local */
float gpa;
printf(”Enter:\n");
char class; printf(" ID#: ");
} Student; scanf("%d",&s.id);
void main() { printf(" GPA: ");
scanf("%f",&s.gpa);
Student s1;
printf(" Class: ");
scanf(" %c",&s.class);
s1 = readS();
printS(s1); s1 return s; /* local as
} id gpa class return val */
}
Structure as Reference Parameter
typedef struct { void readS(Student *s) {
int id; printf(”Enter:\n");
float gpa; printf(" ID#: ");
scanf("%d",&((*s).id));
char class; printf(" GPA: ");
} Student; scanf("%f",&((*s).gpa));
void main() { printf(" Class: ");
scanf(" %c",&((*s).class));
Student s1;
}
/*
readS(&s1); s - address of structure
printS(s1); s1 *s - structure at address
} id gpa class (*s).id - id field of struc
at address */
The Pointer Selection Operator
• Passing a pointer to a structure rather than the
entire structure saves time (need not copy structure)
• Therefore, it is often the case that in functions we
have structure pointers and wish to refer to a field:
(*StrucPtr).Field
• C provides an operator to make this more readable
(the pointer selection operator)
StrucPtr->Field /* equivalent to (*StrucPtr).Field */
• StrucPtr must be a pointer to a structure
• Field must be a name of a field of that type of structure
Pointer Selection Example
typedef struct { void readS(Student *s) {
int id; printf(”Enter:\n");
float gpa; printf(" ID#: ");
scanf("%d",&(s->id));
char class; printf(" GPA: ");
} Student; scanf("%f",&(s->gpa));
void main() { printf(" Class: ");
scanf(" %c",&(s->class));
Student s1;
printf(“Id is %d”,s->id);
readS(&s1); }
printS(s1); s1
} id gpa class
Derived Types as Fields
• The fields of a structure may be any type, including derived types
such as arrays, structures, enumerations, etc.
• An array within a structure is given a field name, to refer to individual
elements of the array we give the field name and then the array ref
([x])
• A structure within a structure is referred to as a nested structure --
there are a couple of ways to declare such structures
Array Within Structure
typedef struct {
s1
int id;
id gpa class
float gpa;
char class;
char name[20];
name
int score[5];
} Student;
012345678 20
Student s1; score
/* With large structure,
more efficient to pass as
pointer */ 0 1 2 3 4
Array Within Structure (cont)
void readS(Student *s) { void printS(Student *s) {
int i; int i;

printf(”Enter:\n"); printf("%s id=#%d (%c)


printf(" Name: "); gpa = %.3f\n",s->name,
scanf("%20s",s->name); s->id,s->class,s->gpa);
printf(" ID#: "); for (i = 0; i < 5; i++)
scanf("%d",&(s->id)); printf("%d ",s->score[i]);
printf(" GPA: "); printf("\n");
scanf("%f",&(s->gpa)); }
printf(" Class: ");
void main() {
scanf(" %c",&(s->class));
Student s1;
printf(" 5 grades: ");
for (i = 0; i < 5; i++)
readS(&s1);
scanf("%d",
printS(&s1);
&(s->score[i]));
}
}
Nested Structure
• Fields of V:
One mechanism, declare nested
V.A /* int field */
structure directly within type
definition: V.D /* structure field */
V.D.B /* char field */
typedef struct {
V.D.C /* float field */
int A;
struct {
char B;
float C; V
} D; /* struc field */ D
A
} MyType; B C

MyType V;
Nested Structure (cont)
Fields of V:
Alternate mechanism (preferred):
V.A /* int field */
typedef struct {
V.D /* structure field */
char B;
V.D.B /* char field */
float C;
V.D.C /* float field */
} MyDType;
typedef struct {
int A;
V
MyDType D;
} MyType; D
A
B C
MyType V;
Initializing Nested Structures
• To initialize a nested structure we give as the value of the structure a
list of values for the substructure:
StrucType V = { Field1Val, Field2Val, Field3Val, … }
where FieldXVal is an item of the form
{ SubField1Val, SubField2Val, SubField3Val, … }
if Field X is a structured field
• Previous example (MyType)
MyType V = { 43, { ‘A’, 3.5 } }; V
D
A
B C
43
A 3.5
Representing Table Data
• For many programs it is appropriate to keep track of a table of
information where we know several things about each entry in the
table:
Name ID Class GPA
Rich 42 F 2.00
Cathy 38 O 3.96
Keith 2 J 3.95
Karen 1 S 4.00
• We would like to keep the values for each entry in the table together
as one unit
Table: Array of Structures
• One mechanism for representing a table of information is to use an array where
each member of the array is a structure representing the info about a line of the
table:

students

id gpa class id gpa class id gpa class


42 2.0 F 38 3.96 O 2 3.95 J

name name name


Ri c h Ca t h y K e i t h

012345678 20 012345678 20 012345678 20


0 1 2
Array of Structures
• Define type corresponding to individual element (structured type)
typedef struct {
/* Fields */
} Student;
• Declare a named array of that type
Student Ss[100];
• Often use an integer variable to keep track of how many of the array
elements are in use:
int numS = 0;
Array of Structures Example
readSFile(Ss,&numS,"stu.dat");
#include <stdio.h> do {
option = select();
#define MAXSTUDENT 100 switch (option) {
case 'I': case 'i':
typedef struct { insS(Ss,&numS); break;
case 'R': case 'r':
int id;
remS(Ss,&numS); break;
float gpa;
case 'P': case 'p':
char class; prntS(Ss,numS); break;
char name[20]; case 'S': case 's':
sort(Ss,numS); break;
} Student;
case 'Q': case 'q': break;
}
void main() {
printf("\n");
Student Ss[MAXSTUDENT]; } while ((option != 'Q') && (option != 'q'));
int numS = 0; prntSFile(Ss,numS,"stu.dat");

int option; }

You might also like