0% found this document useful (0 votes)
45 views

How To Use Dev-C

studentList[0].name

Uploaded by

Minh Hiếu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

How To Use Dev-C

studentList[0].name

Uploaded by

Minh Hiếu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

Dr.

Khoa Dang Do

1
Lecture 8’s Overview
1. Introduction to Enumerations
2. Fundamental about Structures
3. Structures and Functions
4. Introduction to Union

2
1. Introduction to
Enumerations

3
Enumerations
 An enumeration consists of a set of named integer constants

 Keyword enum is used to defined enumerated data type

 type_name is the name of enumerated data type

 value1,value2,....,valueN are values of type type_name

4
Enumerations Definition
enum days {mon, tue, wed, thu, fri, sat, sun};
// Same as:
// #define mon 0
// #define tue 1
// ...
// #define sun 6

enum days {mon=3, tue=8, wed, thu, fri, sat,


sun};
// Same as:
// #define mon 3
// #define tue 8
// #define wed 9
….
// #define sun 13
5
Enumerations Use
enum days day;
// Same as: int day;
for(day = mon; day <= sun; day++)
{
if (day == sun) {
printf("Sun\n");
} else {
printf("day = %d\n", day);
}
}
6
Enumerations Summary

 Basically integers

 Can use in expressions like ints

 Makes code easier to read

 Caution: day++ will always add 1 even if enum


values aren't contiguous.

7
2. Fundamental about
Structures

8
Why Structure?
 Arrays hold many elements of the same type

 What happens if we want to keep a few things


together that are of different types?

 For example, the title, artist and price of the CDs in


a shop

 Or name and telephone number

 Or name, ID number, and mark

9
Structures
 For a limited number of elements

 Of varying types

 Which need to be kept together, in one


place
 We can use a structure

 Like a box, with compartments for


different things

10
Structures
 Like my briefcase, which has
compartments for different shaped
things

 Or a cutlery drawer which has different


sections for teaspoons, knives, forks
and spoons

 Can you think of more examples?

11
Structures
 In C, a structure is known as
a struct
 It contains a fixed number of
parts, which may be of
different types
 So for a friend, you may want
to store name, phone number
and the street they live in
12
Declaring Structures
struct friendStr Every struct needs a
name
{
char name[MAXNAME];
long phoneNumber;
Parts of the struct are
char street[MAXSTREET]; known as members

};

This declares a type of


structure, but it does not
create a variable

13
Declaring structures
 To create a structure in computer memory, you need
to declare a structure variable, like this:
struct friendStr sarah;

name of the variable


name of the type

14
Accessing structures
 To access a member of a structure, you use the '.'
operator, like this:
struct friendStr sarah;
sarah.name
sarah.phoneNumber gives you access to the
value of sarah's name
sarah.street

15
Initialising Structures
struct friendStr
{
char name[MAXNAME];
long phoneNumber;
char street[MAXSTREET];
};
struct friendStr sarah=
{
“John”,5122991941,”Lake Austin Blvd”
};

16
Initialising Structures
struct friendStr
{
char name[MAXNAME];
long phoneNumber;
char street[MAXSTREET];
};
struct friendStr sarah;
scanf("%s",sarah.name);
scanf("%ld",&sarah.phoneNumber);
scanf("%s",sarah.street);

17
Accessing structures
struct friendStr sarah;
scanf("%s",sarah.name);
scanf("%ld",&sarah.phoneNumber);
scanf("%s",sarah.street);

printf("Name is %s\n",sarah.name);
printf("Phone is %d\n",sarah.phoneNumber);
printf("Street is %s\n",sarah.street);

18
Accessing Structures
• A member of a structure is just like any other variable

• If it's a string, it's just an ordinary string

• If it's an int, it's just an ordinary int

• EXCEPT that you access them using the name of the


struct variable, AND the name of the member:

 sarah.phoneNumber = 55559999;
 strcpy(sarah.name,"Sarah Finch");
 strcpy(sarah.street,"Firthsmith St");

19
Accessing structures
• If you want to declare a lot of structs, using "struct
name" all the time is awkward:
struct friendStr sarah;
struct friendStr tony;
struct friendStr quinn;
struct friendStr gunalwan;
struct friendStr fong;

20
Size of a Struct: sizeof
typedef struct
{
double radius; /* 8 bytes */
int x; /* 4 bytes */
int y; /* 4 bytes */
char name[10]; /* 10 bytes */
} Circle;
printf(“Size of Circle struct is %d\n”,
sizeof(Circle));
Size of a Struct
8 + 4 + 4 + 10 = 26
 But sizeof() reports 28 bytes!!!
Most machines require alignment on 4-byte boundary (a
word)
 last word is not filled by the char (2 bytes used, 2 left
over)
DDDD DDDD IIII IIII CCCC CCCC CCXX
8 byte, 2 word double 4 byte, 4 byte, 10 byte char array, 2 bytes
1 word 1 word of the last word unused
integer integer
typedef
• Instead, we can give the struct type a shorter name, like
this:
struct friendStr
{
char name[MAXNAME];
long phoneNumber;
char street[MAXSTREET];
};
typedef struct friendStr friend;

23
typedef
• Now we can use friend everywhere we used to use
struct friendStr
typedef struct friendStr friend;
friend sarah;
friend tony;
friend quinn;
friend gunalwan;
friend fong;

24
typedef
• All we have done is told the compiler: "every
time you see friend, I really mean struct
friendStr."
friendStr.
• In the same way we use symbolic constant
declarations like "#define SIZE 20" to tell
the compiler: "every time you see SIZE, I really
mean 20."
25
typedef
• The other way to use typedef is shorter, like this:

typedef struct {
char name[MAXNAME];

long phoneNumber;

char street[MAXSTREET];

}friend ;

26
Common Mistake
struct StudentRec
{
char lastname[MAXLEN];
float mark;
};

Do not forget the


semicolon here!

27
Notes on structs
 struct variables cannot be compared
 We can perform member comparisons only

if (studA == studB)
{
printf(“Duplicate data.\n”);
}

if (strcmp(studA.lastname, studB.lastname) == 0
&& (studA.mark == studB.mark) )
{
printf(“Duplicate data.\n”);
}

28
Notes on structs (cont)
 We can define a struct, and declare instances of that
struct

struct StudentRec
{
char lastname[MAXLEN];
float mark;
};
struct StudentRec studA, studB;

29
typedef
A typedef statement makes an identifier
equivalent to a type specification
struct StudentRec
Example {
without char lastname[MAXLEN];
typedef float mark;
};

struct StudentRec studentA;

30
typedef (cont)
 The typedef statement makes an identifier
equivalent to a type specification
struct StudentRec
{
Example char lastname[MAXLEN];
with float mark;
typedef
};
typedef struct StudentRec Student;

Student studA;

31
Example with typedef
#include <stdio.h>
#define MAXLEN 50
struct StudentRec{
char lastname[MAXLEN];
float mark;
};
typedef struct StudentRec Student;
int main(){
Student studA;
Student studB;

printf("Enter last name and mark for student A: ");


scanf("%s %f", studA.lastname, &(studA.mark));
printf("Enter last name and mark for student B: ");
scanf("%s %f", studB.lastname, &(studB.mark));

printf("Student A: %s\t%f\n", studA.lastname, studA.mark);


printf("Student B: %s\t%f\n", studB.lastname, studB.mark);

return 0;
} 32
Arrays of structs
 You can have an array of structs

 Each element of the array is a whole struct, with all


the members of that struct.

 So to access a single value, you need to know which


element of the array you're dealing with, and which
member of the struct:
studentList[0].name

studentList[i].id
33
Array of structs
studentList
id:123456789
0
name: "fred"

id:123456788
1
name: "ralph"

id: 123456787
2
name: "fong"

id: 123456786
3
name: "rachel"

34
Array of structs
studentList
id:123456789 studentList[0]gives
0 you the whole struct
name: "fred"

id:123456788
1
name: "ralph"

id: 123456787
2
name: "fong"

id: 123456786
3
name: "rachel"

35
Array of structs
studentList
id:123456789
0
name: "fred"

id:123456788
1
name: "ralph"

id: 123456787
2
name: "fong"

studentList[3].name gives
id: 123456786
3 you the struct member
name: "rachel"

36
Arrays of structs
typedef struct {
long int id;
char name[20];
} Student;
...
Student sem2Class[150];

37
Arrays of structs
Student sem2Class[MAXCLASS];
int i; name of
for (i=0;i<MAXCLASS;i++) array
{
printf("enter name\n");
scanf("%s",sem2Class[i].name);
printf("enter id\n");
scanf("%d",&(sem2Class[i].id));
}

38
Arrays of structs
Student sem2Class[MAXCLASS];
int i;
for (i=0;i<MAXCLASS;i++) index into
array
{
printf("enter name\n");
scanf("%s",sem2Class[i].name);
printf("enter id\n");
scanf("%d",&(sem2Class[i].id));
}

39
Arrays of structs
Student sem2Class[MAXCLASS]; the structure at this
position in the array
int i;
for (i=0;i<MAXCLASS;i++)
{
printf("enter name\n");
scanf("%s",sem2Class[i].name);
printf("enter id\n");
scanf("%d",&(sem2Class[i].id));
}

40
Arrays of structs
Student sem2Class[MAXCLASS]; name of the member
of the structure at
int i;
that position in the
for (i=0;i<MAXCLASS;i++) array
{
printf("enter name\n");
scanf("%s",sem2Class[i].name);
printf("enter id\n");
scanf("%d",&(sem2Class[i].id));
}

41
Arrays of Structures
/* Exercising the horses */
#include <stdio.h>
#include <ctype.h>
int main(void){
struct horse /* Structure declaration */
{
int age;
int height;
char name[20];
char father[20];
char mother[20];
};
42
Arrays of Structures
struct horse My_horses[50]; /* Structure
array declaration */
int hcount = 0; /* Count of the number of
horses */
char test = '\0'; /* Test value for ending
*/
for(hcount = 0; hcount<50 ; hcount++ )
{
printf("\nDo you want to enter details of
a%s horse (Y or N)? ",
hcount?"nother " : "" );
scanf(" %c", &test );

43
Arrays of Structures
if(tolower(test) == 'n')
break;
printf("\nEnter the name of the horse: "
);
scanf("%s", My_horses[hcount].name ); /*
Read the horse's name */
printf("\nHow old is %s? ",
My_horses[hcount].name );
scanf("%d", &My_horses[hcount].age ); /*
Read the horse's age */
printf("\nHow high is %s ( in hands )? ",
My_horses[hcount].name );
44
Arrays of Structures
/* Read the horse's height*/
scanf("%d", &My_horses[hcount].height );
printf("\nWho is %s's father? ",
My_horses[hcount].name );
/* Get the father's name */
scanf("%s", My_horses[hcount].father );
printf("\nWho is %s's mother? ",
My_horses[hcount].name );
/* Get the mother's name */
scanf("%s", My_horses[hcount].mother );
}

45
Arrays of Structures
/* Now tell them what we know. */
for(int i = 0 ; i<hcount ; i++ )
{
printf("\n\n%s is %d years old, %d hands
high,",
My_horses[i].name, My_horses[i].age,
My_horses[i].height);
printf(" and has %s and %s as parents.",
My_horses[i].father,
My_horses[i].mother );
}
return 0;
}
46
Structures in Expressions
 A structure member that is one of the built-in types can
be used like any other variable in an expression.

My_horses[1].height = (My_horses[2].height +
My_horses[3].height)/2;

 You can also use a complete structure element in an


assignment statement
My_horses[1] = My_horses[2];

 All the members of the structure My_horses[2] to be


copied to the structure My_horses[1] 47
Structures in Expressions
 The only other operation that’s possible with a
whole structure is to take its address using the &
operator.

 You can’t add, compare, or perform any other


operations with a complete structure.

 To do those kinds of things, you must write your


own functions

48
Pointers to Structures
 As you can take the address of a structure, the
possibility of declaring a pointer to a structure does,
indeed, naturally follow
struct horse *phorse;
phorse = &My_horses[1];
 So if you want to display the name member of this
structure, you could write this

printf("\nThe name is %s.", (*phorse).name);

49
Pointers to Structures
 There’s another way of doing this, and it’s much
more readable and intuitive.
 You could write the previous statement as follows
printf("\nThe name is %s.", phorse->name );

 You construct the operator -> from a minus sign


immediately followed by the greater-than symbol

50
Dynamic Memory Allocation
for Structures
/* Pointing out the horses */
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h> /* For malloc() */
int main(void){
struct horse{ /* Structure declaration */
int age;
int height;
char name[20];
char father[20];
char mother[20];
}; 51
Dynamic Memory Allocation
for Structures
struct horse *phorse[50]; /* pointer to
structure array declaration */
int hcount = 0; /* Count of the number of
horses */
char test = '\0'; /* Test value for ending
input */
for(hcount = 0; hcount < 50 ; hcount++ ){
printf("\nDo you want to enter details of
a%s horse (Y or N)? ",
hcount?"nother " : "" );
scanf(" %c", &test );
if(tolower(test) == 'n')
break; 52
Dynamic Memory Allocation
for Structures
/* allocate memory to hold a structure */
phorse[hcount] = (struct horse*)
malloc(sizeof(struct horse));
printf("\nEnter the name of the horse: " );
scanf("%s", phorse[hcount]->name ); /* Read
the horse's name */
printf("\nHow old is %s? ", phorse[hcount]-
>name );
scanf("%d", &phorse[hcount]->age ); /* Read
the horse's age */

53
Dynamic Memory Allocation
for Structures
printf("\nHow high is %s ( in hands )? ",
phorse[hcount]->name );
scanf("%d", &phorse[hcount]->height ); /*
Read the horse's height */
printf("\nWho is %s's father? ",
phorse[hcount]->name );
scanf("%s", phorse[hcount]->father ); /* Get
the father's name */
printf("\nWho is %s's mother? ",
phorse[hcount]->name );
scanf("%s", phorse[hcount]->mother ); /* Get
the mother's name */
} 54
Dynamic Memory Allocation
for Structures
/* Now tell them what we know. */
for(int i = 0 ; i < hcount ; i++ )
{
printf("\n\n%s is %d years old, %d hands
high,",
phorse[i]->name, phorse[i]->age, phorse[i]-
>height);
printf(" and has %s and %s as parents.",
phorse[i]->father, phorse[i]->mother);
free(phorse[i]);
}
return 0;
55
}
Structures As Members of a
Structure
struct Date struct horse
{ {
struct Date dob;
int day; int height;
int month; char name[20];
int year; char father[20];
}; char mother[20];
};
struct horse Dobbin;
Dobbin.height = 14;
Dobbin.dob.day = 5;
Dobbin.dob.month = 12;
Dobbin.dob.year = 1962;
56
Pointers to Structures As
Structure Members

 Any pointer can be a member of a structure.


This includes a pointer that points to a
structure

 A pointer structure member that points to the


same type of structure is also permitted

57
Pointers to Structures As
Structure Members
/* Daisy chaining the horses */
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int main(void){
struct horse{ /* Structure declaration */
int age;
int height; char name[20]; char father[20];
char mother[20];
struct horse *next; /* Pointer to next
structure */
}; 58
Pointers to Structures As
Structure Members
struct horse *first = NULL; /* Pointer to
first horse */
struct horse *current = NULL; /* Pointer to
current horse */
struct horse *previous = NULL; /* Pointer to
previous horse */
char test = '\0'; /* Test value for ending
input */
for( ; ; ){
printf("\nDo you want to enter details of a%s
horse (Y or N)? ",

59
Pointers to Structures As
Structure Members
first != NULL?"nother " : "" );
scanf(" %c", &test );
if(tolower(test) == 'n')
break;
/* Allocate memory for a structure */
current = (struct horse*)
malloc(sizeof(struct horse));
if(first == NULL)
first = current; /* Set pointer to first
horse */

60
Pointers to Structures As
Structure Members
if(previous != NULL)
previous -> next = current; /* Set next
pointer for previous horse */
printf("\nEnter the name of the horse: ");
scanf("%s", current -> name); /* Read the
horse's name */
printf("\nHow old is %s? ", current -> name);
scanf("%d", &current -> age); /* Read the
horse's age */
printf("\nHow high is %s ( in hands )? ",
current -> name );
scanf("%d", &current -> height); /* Read the
horse's height */ 61
Pointers to Structures As
Structure Members
printf("\nWho is %s's father? ", current ->
name);
scanf("%s", current -> father); /* Get the
father's name */
printf("\nWho is %s's mother? ", current ->
name);
scanf("%s", current -> mother); /* Get the
mother's name */
current->next = NULL; /* In case it's the
last... */
previous = current; /* Save address of last
horse */
} 62
Pointers to Structures As
Structure Members
/* Now tell them what we know. */
current = first; /* Start at the beginning */
while (current != NULL) /* As long as we have
a valid pointer */
{ /* Output the data*/
printf("\n\n%s is %d years old, %d hands
high,",
current->name, current->age, current-
>height);

63
Pointers to Structures As
Structure Members
printf(" and has %s and %s as parents.",
current->father,
current->mother);
previous = current; /* Save the pointer so we
can free memory */
current = current->next; /* Get the pointer
to the next */
free(previous); /* Free memory for the old
one */
}
return 0;
}
64
Pointers to Structures As
Structure Members

65
3. Structures and
Functions

66
Passing structs as Parameters
 Like any other variable, you can pass a struct as a
parameter to a function

 First we'll look at passing by value

 Pass the struct in, use the values of the members,


but don't change them.
struct StudentRec
{
char lastname[MAXLEN];
float mark;
};
typedef struct StudentRec Student; 67
Passing a struct to a Function
 As always, the formal parameters are copies of the
actual parameters

void printRecord ( Student item )


{
printf("Last name: %s\n", item.lastname);
printf(" Mark: %.1f\n\n", item.mark);
}

main()
{
Student studentA = {“Gauss”, 99.0};
printRecord(studentA);
}
68
Function Returning a struct
 A “package” containing several values

Student readRecord ( void )


{
Student newStudent;
printf("Enter last name and mark: ");
scanf("%s %f",newStudent.lastname,&(newStudent.mark));
return newStudent;
}

main()
{
Student studentA;
studentA = readRecord();
}

69
Example: Structs and Functions-1
#include <stdio.h>
#include <stdlib.h>
#define MAXLEN 50
#define MAXN 20
struct StudentRec{
char lastname[MAXLEN];
float mark;
};
typedef struct StudentRec Student;

Student readRecord ( void ){


Student newStudent;
printf("Enter last name and mark: ");
scanf("%s %f", newStudent.lastname, &(newStudent.mark));
return newStudent;
}

void printRecord ( Student item ){


printf("Last name: %s\n", item.lastname);
printf(" Mark: %.1f\n\n", item.mark);
}

70
Example: Structs and Functions-2
int main()
{
int count = 0;
Student class[MAXN];
int i;
printf("How many students? ");
scanf("%d", &count);
if (count > MAXN)
{
printf("Not enough space.\n");
exit(1);
}

for (i=0; i < count; i++)


{
class[i] = readRecord();
}
printf("\nClass list:\n\n");
for (i=0; i < count; i++)
{
printRecord(class[i]);
}
return 0;
}
71
Passing structs as parameters

 You can also pass structs by reference

 Pass the struct in, change the value of some or all


of the members, changes are visible in the calling
function as well as the called function.

 This time you're passing a pointer to a struct

72
Passing structs by reference
void readStudent ( Student* item )
{
printf(“Please enter name and ID\n”);
scanf(“%s”, (*s).name) /*parens needed*/
scanf(“%ld”, &((*s).id) ); /* Yes! */
}

int main()
{
Student studentA;
readStudent(&studentA);
}

73
Passing structs by reference
 The parentheses around the (*s) are needed
because of precedence

 We frequently have (*sptr).item

 If you need the address of an item referred to this


way, you need another set of parentheses

 We frequently have &((*sptr).item)

74
Using arrays and pointers
 Some struct: s[13]

 An item in some struct: s[4].age

 A character in some name: s[7].name[3]

 Address of some struct: &(s[2])

 An item in some struct pointed to: (*sptr).age

 Address of above: &((*sptr).age)

This is an address within a struct


75
4. Introduction to Union

76
Union Definition
 You can share memory between a number of variables

 When your program processes a number of different


kinds of data record, but only one kind at a time
 The kind to be processed is determined at execution
time
 The facility in C that allows the same memory area to
be shared by a number of different variables is called
a union
77
Union Definition
union u_example
{
float decval;
int *pnum;
double my_value;
} U1;
 Members of a union are accessed in exactly the same
way as members of a structure

U1.decval = 2.5;
78
Using Union
/* The operation of a union */
#include <stdio.h>
int main(void)
{
union u_example
{
float decval;
int pnum;
double my_value;
} U1;
79
Using Union
U1.my_value = 125.5;
U1.pnum = 10;
U1.decval = 1000.5f;
printf("\ndecval = %f pnum = %d
my_value = %lf",
U1.decval, U1.pnum, U1.my_value );
printf("\nU1 size = %d\ndecval size =
%d pnum size = %d my_value"
" size = %d",sizeof U1, sizeof
U1.decval,
sizeof U1.pnum, sizeof U1.my_value);
return 0;} 80
Using Union

The first thing to note is that the last variable that was assigned a
value is correct, and the other two have been corrupted

81
Pointers to Unions
union u_example *pU;
pU = &U2;
U1.decval = pU->decval;

 The expression on the right of the second assignment


is equivalent to U2.decval.

82
Structures As Union Members
struct
 Structures and arrays my_structure
can be members of a {
int num1;
union
float num2;
 It’s also possible for a union
union to be a member {
of a structure int *pnum;
float *pfnum;
} my_U
} samples[5]; 83

You might also like