Professional Documents
Culture Documents
Lecture 09-1
Lecture 09-1
Lecture 09-1
9
C Structures, Unions, Bit
Manipulations and
Enumerations
2
課程目標
▪ Introduction
▪ Structure Definitions
▪ Initializing Structures
▪ Accessing Members of Structures
▪ Using Structures with Functions
▪ typedef
▪ Unions
▪ Bitwise Operators
▪ Bit Fields
▪ Enumeration Constants
3
Main Topics
▪ Structure
– Collections of related variables (aggregates) under
one name
– Can contain variables of different data types
– Commonly used to define records to be stored in
files
– Combined with pointers, can create linked lists,
stacks, queues, and trees
▪ Union
– Allowed data type being overloaded
▪ Bit fields
▪ Enumeration
4
C Program Design
C Structures, Unions, Bit
Manipulations and Enumerations
▪ Structure Definitions
5
Structure Definitions
struct PersonalData
{
char name[NAMESIZE];
char address[ADDRSIZE];
int YearOfBirth;
int MonthOfBirth;
int DayOfBirth;
};
struct PersonalData
{
char name[NAMESIZE];
char address[ADDRSIZE];
int YearOfBirth;
int MonthOfBirth;
int DayOfBirth;
};
struct PersonalData
{
struct
char PersonalData
name[NAMESIZE];
{
char address[ADDRSIZE];
int char name[NAMESIZE];
YearOfBirth;
int char address[ADDRSIZE];
MonthOfBirth;
int int YearOfBirth;
DayOfBirth;
}; int MonthOfBirth;
int DayOfBirth;
} teacher,
struct students[51],
PersonalData teacher, *p;
students[51], *p;
// variable identifier follows type
8
struct PersonalData
{
struct
char PersonalData
name[NAMESIZE];
{
char address[ADDRSIZE];
typedef struct _tagPersonalData
int char name[namesize];
YearOfBirth;
{
int char address[addresssize];
MonthOfBirth;
char name[NAMESIZE];
int int YearOfBirth;
DayOfBirth;
char address[ADDRSIZE];
}; int MonthOfBirth;
int YearOfBirth;
int DayOfBirth;
int students[51],
} teacher, MonthOfBirth; *p;
struct PersonalData
int teacher, students[51], *p;
DayOfBirth;
// variable identifier follows type
} PersonalData;
#define NAMESIZE 50
Example #define ADDRSIZE
struct PersonalData
80
{
char name[NAMESIZE];
char address[ADDRSIZE];
int YearOfBirth;
int MonthOfBirth;
int DayOfBirth;
};
main()
{
struct PersonalData student;
printf("\n\n");
#define NAMESIZE 50
Example #define ADDRSIZE
struct PersonalData
80
{
char name[NAMESIZE];
char address[ADDRSIZE];
int YearOfBirth;
int MonthOfBirth;
int DayOfBirth;
};
main()
{
struct PersonalData student;
printf("\n\n");
#define NAMESIZE 50
Example #define ADDRSIZE
struct PersonalData
80
{
char name[NAMESIZE];
char address[ADDRSIZE];
int YearOfBirth;
int MonthOfBirth;
int DayOfBirth;
};
main()
{
struct PersonalData student;
printf("\n\n");
main()
{
struct PersonalData student;
printf("\n\n");
sizeof Operator
struct SomeData
{
char aChar;
int anInt;
float aFloat;
double aDouble;
};
sizeof(struct SomeData) = ?
17
#include <stdio.h>
sizeof Operator
#include <limits.h>
#include <float.h>
struct SomeData
{
char aChar;
int anInt;
float aFloat;
double aDouble;
};
main()
{
char mark[]={'M', 'A', 'R', 'K'};
struct SomeData x;
#include <stdio.h>
sizeof Operator
#include <limits.h>
#include <float.h>
struct SomeData
{
char aChar;
int anInt;
float aFloat;
double aDouble;
};
main()
{
char mark[]={'M', 'A', 'R', 'K'};
struct SomeData x;
sizeof Operator
sizeof(struct SomeData) = ?
20
C Program Design
C Structures, Unions, Bit
Manipulations and Enumerations
▪ Initializing Structures
21
Example
// person.c
#include <stdio.h>
#include "person.h"
Example
// person.c
#include <stdio.h>
#include "person.h"
// main.c
void getPersonInfo(struct PersonalData *p)
#include <stdio.h>
{ #include "person.h"
printf("Enter name: ");
gets(p->name);
main() address: ");
printf("Enter
{
gets(p->address);
struct
printf("Enter PersonalData
birthday: student = {
yy/mm/dd: ");
// person.h scanf("%2d/%2d/%2d", &p->YearOfBirth,
"Hale-Evans, Ron",
#define NAMESIZE 50 &p->MonthOfBirth, &p->DayOfBirth);
#define ADDRSIZE 80
"Seattle, Washington",
}
struct PersonalData 1965,
{ 6,
void showPersonInfo(struct PersonalData *p)
char name[NAMESIZE]; { 27
char address[ADDRSIZE]; }; %s\n", p->name);
printf("Name:
int YearOfBirth; printf("Address: %s\n", p->address);
int MonthOfBirth; printf("Bithday: %2d/%2d/%2d\n", p->YearOfBirth,
int DayOfBirth;
// Print out the student record
p->MonthOfBirth, p->DayOfBirth);
}; showPersonInfo(&student);
}
}
void getPersonInfo(struct PersonalData *);
void showPersonInfo(struct PersonalData *);
23
Example
// person.c
#include <stdio.h>
#include "person.h"
// main.c
#include <stdio.h> void getPersonInfo(struct PersonalData *p)
#include "person.h" {
printf("Enter name: ");
main() gets(p->name);
printf("Enter address: ");
{
gets(p->address);
struct PersonalData persons[] = {
printf("Enter birthday: yy/mm/dd: ");
// person.h{"Hale-Evans, Ron", "Seattle, Washington", 1965, 6, 27},
scanf("%2d/%2d/%2d", &p->YearOfBirth,
#define NAMESIZE 50
{"Liddell, Alice", "Wonderland", 1852, 5, 4},
&p->MonthOfBirth, &p->DayOfBirth);
#define ADDRSIZE 80 } "The Galaxy", 1961, 11, 15}
{"Adams, Douglas",
struct PersonalData
{
};
void showPersonInfo(struct PersonalData *p)
struct
char PersonalData *p;
name[NAMESIZE]; {
int address[ADDRSIZE];
char i; printf("Name: %s\n", p->name);
int YearOfBirth; printf("Address: %s\n", p->address);
int
// MonthOfBirth;
Print out the records printf("Bithday: %2d/%2d/%2d\n", p->YearOfBirth,
int DayOfBirth;
for(i p->MonthOfBirth, p->DayOfBirth);
= 0, p = persons; i < sizeof(persons)/sizeof(struct PersonalData); i++){
}; }
ShowPersonInfo(p++);
printf("\n"); PersonalData *);
void getPersonInfo(struct
void }showPersonInfo(struct PersonalData *);
}
24
Example
// person.c
#include <stdio.h>
#include "person.h"
// main.c
#include <stdio.h> void getPersonInfo(struct PersonalData *p)
#include "person.h" {
printf("Enter name: ");
main() gets(p->name);
printf("Enter address: ");
{
gets(p->address);
struct PersonalData persons[] = {
printf("Enter birthday: yy/mm/dd: ");
// person.h{"Hale-Evans, Ron", "Seattle, Washington", 1965, 6, 27},
scanf("%2d/%2d/%2d", &p->YearOfBirth,
#define NAMESIZE 50
{"Liddell, Alice", "Wonderland", 1852, 5, 4},
&p->MonthOfBirth, &p->DayOfBirth);
#define ADDRSIZE 80 } "The Galaxy", 1961, 11, 15}
{"Adams, Douglas",
struct PersonalData
{
};
void showPersonInfo(struct PersonalData *p)
struct
char PersonalData *p;
name[NAMESIZE]; {
int address[ADDRSIZE];
char i; printf("Name: %s\n", p->name);
int YearOfBirth; printf("Address: %s\n", p->address);
int
// MonthOfBirth;
Print out the records printf("Bithday: %2d/%2d/%2d\n", p->YearOfBirth,
int DayOfBirth;
for(i p->MonthOfBirth, p->DayOfBirth);
= 0, p = persons; i < sizeof(persons)/sizeof(struct PersonalData); i++){
}; }
ShowPersonInfo(p++);
printf("\n"); PersonalData *);
void getPersonInfo(struct
void }showPersonInfo(struct PersonalData *);
}
25
Example
// person.c
#include <stdio.h>
#include "person.h"
// main.c
#include <stdio.h> void getPersonInfo(struct PersonalData *p)
#include "person.h" {
printf("Enter name: ");
main() gets(p->name);
printf("Enter address: ");
{
gets(p->address);
struct PersonalData persons[] = {
printf("Enter birthday: yy/mm/dd: ");
// person.h{"Hale-Evans, Ron", "Seattle, Washington", 1965, 6, 27},
scanf("%2d/%2d/%2d", &p->YearOfBirth,
#define NAMESIZE 50
{"Liddell, Alice", "Wonderland", 1852, 5, 4},
&p->MonthOfBirth, &p->DayOfBirth);
#define ADDRSIZE 80 } "The Galaxy", 1961, 11, 15}
{"Adams, Douglas",
struct PersonalData
{
};
void showPersonInfo(struct PersonalData *p)
struct
char PersonalData *p;
name[NAMESIZE]; {
int address[ADDRSIZE];
char i; printf("Name: %s\n", p->name);
int YearOfBirth; printf("Address: %s\n", p->address);
int
// MonthOfBirth;
Print out the records printf("Bithday: %2d/%2d/%2d\n", p->YearOfBirth,
int DayOfBirth;
for(i p->MonthOfBirth, p->DayOfBirth);
= 0, p = persons; i < sizeof(persons)/sizeof(struct PersonalData); i++){
}; }
ShowPersonInfo(p++);
printf("\n"); PersonalData *);
void getPersonInfo(struct
void }showPersonInfo(struct PersonalData *);
}
26
Initializing Structures
Initializing Structures
C Program Design
C Structures, Unions, Bit
Manipulations and Enumerations
▪ Accessing Members of Structures
29
▪ Dot operator
struct PersonalData(.) for*p;
friend, structure variables
p struct
= &friend;
PersonalData friend;
strcpy((*p).name, "George Lin");
strcpy(friend.name, "George Lin");
strcpy((*p).address, "Taipei Taiwan");
strcpy(friend.address,
(*p).YearOfBirth "Taipei Taiwan");
= 1978;
friend.YearOfBirth = 1978;= 12;
(*p).friend.MonthOfBirth
equivalent
(*p).DayOfBirth = 24;
friend.MonthOfBirth = 12;
friend.DayOfBirth = 24;
C Program Design
C Structures, Unions, Bit
Manipulations and Enumerations
▪ Passing Reference
// complex.c
#include "complex.h"
return c;
}
// main.c
#include <stdio.h>
// complex.c
#include "complex.h"
#include "complex.h"
main()
Complex AddByVal(Complex a, Complex b)
{
{
Complex x = {12.0, 5};
Complex c;
Complex y = {4.0, 8.0};
Complex z, w;
c.real = a.real + b.real;
c.imag = a.imag + b.imag;
// Call by value
z = AddByVal(x, y);
return c;
printf("(%.1f + i%.1f) + (%.1f + i%.1f) = (%.1f + i%.1f)\n",
}
x.real, x.imag, y.real, y.imag, z.real, z.imag);
void AddByRef(Complex* a, Complex* b, Complex* c)
// Call by reference
{
AddByRef(&x, &y , &w);
c->real = a->real + b->real;
printf("(%.1f + i%.1f) + (%.1f + i%.1f) = (%.1f + i%.1f)\n",
c->imag = a->imag + b->imag;
x.real, x.imag, y.real, y.imag, w.real, w.imag);
}
}
35
C Program Design
C Structures, Unions, Bit
Manipulations and Enumerations
▪typedef
37
typedef
typedef type-declaration synonym;
Example
// complex.h
struct _tagComplex
{
double real;
double imag;
};
// complex.h
struct _tagComplex
// SomeTypeDef.h {
double real;
#include "complex.h" double imag;
};
#include <stdio.h>
// complex.h
#include "SomeTypedef.h" struct _tagComplex
{
double real;
double imag;
ARITHOP arith[4]={sum, substract, mul, div}; };
{
Complex AddByVal(Complex, Complex);
INT val1, val2, op; void AddByRef(ptrComplex, ptrComplex, ptrComplex);
#include <stdio.h>
// complex.h
#include "SomeTypedef.h" struct _tagComplex
{
double real;
double imag;
ARITHOP arith[4]={sum, substract, mul, div}; };
{
Complex AddByVal(Complex, Complex);
INT val1, val2, op; void AddByRef(ptrComplex, ptrComplex, ptrComplex);
C Program Design
C Structures, Unions, Bit
Manipulations and Enumerations
▪Unions
45
union
▪ It is sometimes desirable to define a variable
which can be of two or more different types
according to different circumstances
(overloading).
▪ The distinction between a union and a structure:
– The members of a structure define different
variables
– The members of a union define different
manifestations of the same variable.
▪ The space need only be allocated to
accommodate the largest type specified in a
union.
46
union Definition
REMARK rem;
union Remark {
int age;
double tall;
char month[4];
sizeof(union Remark)=?
};
sizeof(REMARK)=?
union Remark rem;
47
Example // main.c
#include <stdio.h>
#include <string.h>
#include "remark.h"
Example // main.c
#include <stdio.h>
#include <string.h>
#include "remark.h"
C Program Design
C Structures, Unions, Bit
Manipulations and Enumerations
▪Bitwise Operators
51
Bits
▪ All data is represented internally as
sequences of bits
– Each bit can be either 0 or 1
– Sequence of 8 bits forms a byte
Bitwise Operators
Operator Description
& bitwise AND The bits in the result are set to 1 if the corresponding bits
in the two operands are both 1 .
| bitwise inclusive The bits in the result are set to 1 if at least one of the corresponding bits
OR in the two operands is 1.
^ bitwise exclusive The bits in the result are set to 1 if exactly one of the corresponding bits
OR in the two operands is 1.
<< left shift Shifts the bits of the first operand left by the number of bits specified by
the second operand; fill from the right with 0 bits.
>> right shift Shifts the bits of the first operand right by the number of bits specified by
the second operand; the method of filling from the left is machine
dependent.
~ one’s complement All 0 bits are set to 1 and all 1 bits are set to 0.
53
Example (I)
// displayBits.c
putchar( '\n' );
} /* end function displayBits */
54
Example (I)
// main.c
#include <stdio.h>
// displayBits.c
void displayBits( unsigned value ); // prototype
void displayBits( unsigned value )
{ int main( void )
unsigned c; // counter {
unsigned
unsigned displayMask = 1 << 31; // x; // variable to hold user input
displayMask
while(1){
printf( "%10u = ", value );
printf( "Enter an unsigned integer: " );
scanf(
for ( c = 1; c <= 32; c++ ) {// loop"%u", &x );
through bits
putchar( value & displayMask ? '1' : '0' );
value <<= 1; // shift valuedisplayBits(
left by 1 x );
}
// output space per 8 bits
if ( c % 8 == 0 ) putchar( ' ' );
} /* end for */ return 0; // indicates successful termination
Example (I)
// main.c
#include <stdio.h>
// displayBits.c
void displayBits( unsigned value ); // prototype
void displayBits( unsigned value )
{ int main( void )
unsigned c; // counter {
unsigned
unsigned displayMask = 1 << 31; // x; // variable to hold user input
displayMask
while(1){
printf( "%10u = ", value );
printf( "Enter an unsigned integer: " );
scanf(
for ( c = 1; c <= 32; c++ ) {// loop"%u", &x );
through bits
putchar( value & displayMask ? '1' : '0' );
value <<= 1; // shift valuedisplayBits(
left by 1 x );
}
// output space per 8 bits
if ( c % 8 == 0 ) putchar( ' ' );
} /* end for */ return 0; // indicates successful termination
Example (II)
// displayBits.c
putchar( '\n' );
} /* end function displayBits */
57
Example (II)
// main.c
#include <stdio.h>
on off
Example:
G 0100 0111 4 4
o 0110 1111 6 2
Boy.txt o 0110 1111 6 2
d 0110 0100 3 5
Good boy. 0010 0000 1 7
b 0110 0010 3 5
o 0110 1111 6 2
y 0111 1001 5 3
. 0010 1110 4 4
38 34
64
on off
Example:
G 01000111 4 4
o 01101111 6 2
Boy.txt o 01101111 6 2
d 01100100 3 5
Good boy. 00100000 1 7
b 0110 0010 3 5
o 0110 1111 6 2
There are 38 on-bits yand 34
0111 5 in file
off-bits
1001 3 Boy.txt.
. 0010 1110 4 4
38 34
65
▪ int bitson(char c)
returns number of on-bit in c
▪ int bitsoff(char c)
returns number of off-bit in c
67
C Program Design
C Structures, Unions, Bit
Manipulations and Enumerations
▪Bit Fields
68
sizeof(struct Card) = ?
struct Card {
unsigned face;
unsigned suit;
unsigned color;
};
69
Bit Fields
▪ When storage space is at a premium,
it may be necessary to pack several
objects into a single machine storage
unit.
suit
color face
70
struct BitCard {
unsigned face : 4;
unsigned suit : 2; sizeof(struct BitCard) = ?
unsigned color: 1;
};
suit
color face
71
struct BitCard {
unsigned face : 4;
unsigned suit : 2;
unsigned color: 1;
};
Example
// Cards.h
typedef struct bitCard Card; // new type name for struct bitCard
#include <stdio.h> typedef struct bitCard Card; // new type name for struct bitCard
#include "Cards.h" void fillDeck( Card * const wDeck ); // prototype
void fillDeck( Card * const wDeck ) void deal( const Card * const wDeck ); // prototype
{
int i; /* counter */
#include <stdio.h> typedef struct bitCard Card; // new type name for struct bitCard
#include "Cards.h" void fillDeck( Card * const wDeck ); // prototype
void fillDeck( Card * const wDeck ) void deal( const Card * const wDeck ); // prototype
{
int i; /* counter */
//
for (main.c
i = 0; i <= 51; i++ ) {
wDeck[ i ].face = i % 13;
#include <stdio.h>
wDeck[ i ].suit = i / 13;
#include
}
"Cards.h“
wDeck[ i ].color = i / 26;
typedef struct bitCard Card; // new type name for struct bitCard
// main.c
#include <stdio.h>
#include "Cards.h"
#include <stdio.h>
void fillDeck( Card * const wDeck ) #include "Cards.h“
{
int i; /* counter */
int main( void )
for ( i = 0; i <= 51; i++ ) { {
wDeck[ i ].face = i % 13; Card deck[ 52 ]; // create array of Cards
wDeck[ i ].suit = i / 13;
wDeck[ i ].color = i / 26;
} fillDeck( deck );
} deal( deck );
void deal( const Card * const wDeck )
}
{
int k1; /* subscripts 0-25 */
int k2; /* subscripts 26-51 */
Example
struct UnnameExample {
/* field 4 bits wide */
unsigned field1 :4;
/* one-bit field
* can only be 0 or -1 in two's complement! */
signed field2 :1;
C Program Design
C Structures, Unions, Bit
Manipulations and Enumerations
▪Enumeration
Constants
79
Enumeration
Enumeration
enum Suits {CLUB, DIMOND, SPADE, HEART};
Example
#include <stdio.h>
Example
#include <stdio.h>
More Examples