SlideShare a Scribd company logo
1 of 19
Outline
Introduction
Structure Definitions
Initializing Structures
Accessing Members of Structures
Using Structures with Functions
Typedef
Example: High-Performance Card Shuffling and
Dealing Simulation
Unions
 Structures
◦ 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
 Example
struct card {
char *face;
char *suit;
};
◦ struct introduces the definition for structure card
◦ card is the structure name and is used to declare
variables of the structure type
◦ card contains two members of type char * -
face and suit
 Struct information
◦ A struct cannot contain an instance of itself
◦ Can contain a member that is a pointer to the same
structure type
◦ Structure definition does not reserve space in memory
◦ Creates a new data type that used to declare structure
variables.
 Declarations
◦ Declared like other variables:
card oneCard, deck[ 52 ], *cPtr;
◦ Can use a comma separated list:
struct card {
char *face;
char *suit;
} oneCard, deck[ 52 ], *cPtr;
 Valid Operations
◦ Assigning a structure to a structure of the same type
◦ Taking the address (&) of a structure
◦ Accessing the members of a structure
◦ Using the sizeof operator to determine the size of a
structure
 Initializer lists
◦ Example:
card oneCard = { "Three", "Hearts" };
 Assignment statements
◦ Example:
card threeHearts = oneCard;
◦ Or:
card threeHearts;
threeHearts.face = “Three”;
threeHearts.suit = “Hearts”;
 Accessing structure members
◦ Dot operator (.) - use with structure variable name
card myCard;
printf( "%s", myCard.suit );
◦ Arrow operator (->) - use with pointers to structure
variables
card *myCardPtr = &myCard;
printf( "%s", myCardPtr->suit );
myCardPtr->suit equivalent to
( *myCardPtr ).suit
 Passing structures to functions
◦ Pass entire structure
 Or, pass individual members
◦ Both pass call by value
 To pass structures call-by-reference
◦ Pass its address
◦ Pass reference to it
 To pass arrays call-by-value
◦ Create a structure with the array as a member
◦ Pass the structure
 typedef
◦ Creates synonyms (aliases) for previously defined
data types
◦ Use typedef to create shorter type names.
◦ Example:
typedef Card *CardPtr;
◦ Defines a new type name CardPtr as a synonym for type
Card *
◦ typedef does not create a new data type
 Only creates an alias
 Pseudocode:
◦ Create an array of card structures
◦ Put cards in the deck
◦ Shuffle the deck
◦ Deal the cards
1. Load headers
1.1 Define struct
1.2 Function
prototypes
1.3 Initialize deck[]
and face[]
1.4 Initialize suit[]
1 /* Fig. 10.3: fig10_03.c
2 The card shuffling and dealing program using structures */
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <time.h>
6
7 struct card {
8 const char *face;
9 const char *suit;
10 };
11
12 typedef struct card Card;
13
14 void fillDeck( Card * const, const char *[],
15 const char *[] );
16 void shuffle( Card * const );
17 void deal( const Card * const );
18
19 int main()
20 {
21 Card deck[ 52 ];
22 const char *face[] = { "Ace", "Deuce", "Three",
23 "Four", "Five",
24 "Six", "Seven", "Eight",
25 "Nine", "Ten",
26 "Jack", "Queen", "King"};
27 const char *suit[] = { "Hearts", "Diamonds",
28 "Clubs", "Spades"};
29
30 srand( time( NULL ) );
2. Randomize
2. fillDeck
2.1 shuffle
2.2 deal
3. Function definitions
31
32 fillDeck( deck, face, suit );
33 shuffle( deck );
34 deal( deck );
35 return 0;
36 }
37
38 void fillDeck( Card * const wDeck, const char * wFace[],
39 const char * wSuit[] )
40 {
41 int i;
42
43 for ( i = 0; i <= 51; i++ ) {
44 wDeck[ i ].face = wFace[ i % 13 ];
45 wDeck[ i ].suit = wSuit[ i / 13 ];
46 }
47 }
48
49 void shuffle( Card * const wDeck )
50 {
51 int i, j;
52 Card temp;
53
54 for ( i = 0; i <= 51; i++ ) {
55 j = rand() % 52;
56 temp = wDeck[ i ];
57 wDeck[ i ] = wDeck[ j ];
58 wDeck[ j ] = temp;
59 }
60 }
Put all 52 cards in the deck.
face and suit determined by
remainder (modulus).
Select random number between 0 and 51.
Swap element i with that element.
3. Function definitions
61
62 void deal( const Card * const wDeck )
63 {
64 int i;
65
66 for ( i = 0; i <= 51; i++ )
67 printf( "%5s of %-8s%c", wDeck[ i ].face,
68 wDeck[ i ].suit,
69 ( i + 1 ) % 2 ? 't' : 'n' );
70 }
Cycle through array and print
out data.
Program Output
Eight of Diamonds Ace of Hearts
Eight of Clubs Five of Spades
Seven of Hearts Deuce of Diamonds
Ace of Clubs Ten of Diamonds
Deuce of Spades Six of Diamonds
Seven of Spades Deuce of Clubs
Jack of Clubs Ten of Spades
King of Hearts Jack of Diamonds
Three of Hearts Three of Diamonds
Three of Clubs Nine of Clubs
Ten of Hearts Deuce of Hearts
Ten of Clubs Seven of Diamonds
Six of Clubs Queen of Spades
Six of Hearts Three of Spades
Nine of Diamonds Ace of Diamonds
Jack of Spades Five of Clubs
King of Diamonds Seven of Clubs
Nine of Spades Four of Hearts
Six of Spades Eight of Spades
Queen of Diamonds Five of Diamonds
Ace of Spades Nine of Hearts
King of Clubs Five of Hearts
King of Spades Four of Diamonds
Queen of Hearts Eight of Hearts
Four of Spades Jack of Hearts
Four of Clubs Queen of Clubs
 union
◦ Memory that contains a variety of objects over time
◦ Only contains one data member at a time
◦ Members of a union share space
◦ Conserves storage
◦ Only the last data member defined can be accessed
 union declarations
◦ Same as struct
union Number {
int x;
float y;
};
Union myObject;
 Valid union operations
◦ Assignment to union of same type: =
◦ Taking address: &
◦ Accessing union members: .
◦ Accessing members using pointers: ->
1. Define union
1.1 Initialize variables
2. Set variables
3. Print
1 /* Fig. 10.5: fig10_05.c
2 An example of a union */
3 #include <stdio.h>
4
5 union number {
6 int x;
7 double y;
8 };
9
10 int main()
11 {
12 union number value;
13
14 value.x = 100;
15 printf( "%sn%sn%s%dn%s%fnn",
16 "Put a value in the integer member",
17 "and print both members.",
18 "int: ", value.x,
19 "double:n", value.y );
20
21 value.y = 100.0;
22 printf( "%sn%sn%s%dn%s%fn",
23 "Put a value in the floating member",
24 "and print both members.",
25 "int: ", value.x,
26 "double:n", value.y );
27 return 0;
28 }
Program Output
Put a value in the integer member
and print both members.
int: 100
double:
-92559592117433136000000000000000000000000000000000000000000000.00000
Put a value in the floating member
and print both members.
int: 0
double:
100.000000
Program Output
1 January
2 February
3 March
4 April
5 May
6 June
7 July
8 August
9 September
10 October
11 November
12 December

More Related Content

What's hot (7)

Inheritance
InheritanceInheritance
Inheritance
 
Neo4 j
Neo4 jNeo4 j
Neo4 j
 
About Array
About ArrayAbout Array
About Array
 
Arrays, Structures And Enums
Arrays, Structures And EnumsArrays, Structures And Enums
Arrays, Structures And Enums
 
Introduction towebmatrix
Introduction towebmatrixIntroduction towebmatrix
Introduction towebmatrix
 
Lecture 04
Lecture 04Lecture 04
Lecture 04
 
Pointers
PointersPointers
Pointers
 

Viewers also liked

Certificate_28
Certificate_28Certificate_28
Certificate_28Adeel Khan
 
Exhibiting the Photobook
Exhibiting the PhotobookExhibiting the Photobook
Exhibiting the PhotobookStephen Clarke
 
MatisseFall_2015_lr
MatisseFall_2015_lrMatisseFall_2015_lr
MatisseFall_2015_lrSheena Parks
 
Castañada 2015.Pereda:Leganés
Castañada 2015.Pereda:LeganésCastañada 2015.Pereda:Leganés
Castañada 2015.Pereda:Leganésevax14
 
Tugas ergonomi hasna
Tugas ergonomi hasnaTugas ergonomi hasna
Tugas ergonomi hasnahananhasna
 
Certificate_27
Certificate_27Certificate_27
Certificate_27Adeel Khan
 
Samsung Techwin SCP-3120 Data Sheet
Samsung Techwin SCP-3120 Data SheetSamsung Techwin SCP-3120 Data Sheet
Samsung Techwin SCP-3120 Data SheetJMAC Supply
 
Samsung Techwin SCP-2370H Data Sheet
Samsung Techwin SCP-2370H Data SheetSamsung Techwin SCP-2370H Data Sheet
Samsung Techwin SCP-2370H Data SheetJMAC Supply
 
Samsung Techwin SCP-3370H Data Sheet
Samsung Techwin SCP-3370H Data SheetSamsung Techwin SCP-3370H Data Sheet
Samsung Techwin SCP-3370H Data SheetJMAC Supply
 
Power Point from 2nd City Disability studies in Education COnference, CHicago...
Power Point from 2nd City Disability studies in Education COnference, CHicago...Power Point from 2nd City Disability studies in Education COnference, CHicago...
Power Point from 2nd City Disability studies in Education COnference, CHicago...Jane Strauss
 
Certificate_25
Certificate_25Certificate_25
Certificate_25Adeel Khan
 
Samsung Techwin SCP-2370TH Data Sheet
Samsung Techwin SCP-2370TH Data SheetSamsung Techwin SCP-2370TH Data Sheet
Samsung Techwin SCP-2370TH Data SheetJMAC Supply
 
Samsung Techwin SCP-3371H Data Sheet
Samsung Techwin SCP-3371H Data SheetSamsung Techwin SCP-3371H Data Sheet
Samsung Techwin SCP-3371H Data SheetJMAC Supply
 
Samsung Techwin SCP-3120VH Data Sheet
Samsung Techwin SCP-3120VH Data SheetSamsung Techwin SCP-3120VH Data Sheet
Samsung Techwin SCP-3120VH Data SheetJMAC Supply
 
Planificador de proyectos plantilla grupo 70
Planificador de proyectos plantilla grupo 70Planificador de proyectos plantilla grupo 70
Planificador de proyectos plantilla grupo 70Alvaro Avendaño Arias
 

Viewers also liked (19)

Certificate_28
Certificate_28Certificate_28
Certificate_28
 
Exhibiting the Photobook
Exhibiting the PhotobookExhibiting the Photobook
Exhibiting the Photobook
 
MatisseFall_2015_lr
MatisseFall_2015_lrMatisseFall_2015_lr
MatisseFall_2015_lr
 
Castañada 2015.Pereda:Leganés
Castañada 2015.Pereda:LeganésCastañada 2015.Pereda:Leganés
Castañada 2015.Pereda:Leganés
 
8. процедуры
8. процедуры8. процедуры
8. процедуры
 
Tugas ergonomi hasna
Tugas ergonomi hasnaTugas ergonomi hasna
Tugas ergonomi hasna
 
Certificate_27
Certificate_27Certificate_27
Certificate_27
 
Samsung Techwin SCP-3120 Data Sheet
Samsung Techwin SCP-3120 Data SheetSamsung Techwin SCP-3120 Data Sheet
Samsung Techwin SCP-3120 Data Sheet
 
Samsung Techwin SCP-2370H Data Sheet
Samsung Techwin SCP-2370H Data SheetSamsung Techwin SCP-2370H Data Sheet
Samsung Techwin SCP-2370H Data Sheet
 
Samsung Techwin SCP-3370H Data Sheet
Samsung Techwin SCP-3370H Data SheetSamsung Techwin SCP-3370H Data Sheet
Samsung Techwin SCP-3370H Data Sheet
 
Power Point from 2nd City Disability studies in Education COnference, CHicago...
Power Point from 2nd City Disability studies in Education COnference, CHicago...Power Point from 2nd City Disability studies in Education COnference, CHicago...
Power Point from 2nd City Disability studies in Education COnference, CHicago...
 
Certificate_25
Certificate_25Certificate_25
Certificate_25
 
9. баллы
9. баллы9. баллы
9. баллы
 
Samsung Techwin SCP-2370TH Data Sheet
Samsung Techwin SCP-2370TH Data SheetSamsung Techwin SCP-2370TH Data Sheet
Samsung Techwin SCP-2370TH Data Sheet
 
Samsung Techwin SCP-3371H Data Sheet
Samsung Techwin SCP-3371H Data SheetSamsung Techwin SCP-3371H Data Sheet
Samsung Techwin SCP-3371H Data Sheet
 
Quick facts 11515
Quick facts 11515Quick facts 11515
Quick facts 11515
 
Poster FINAL
Poster FINALPoster FINAL
Poster FINAL
 
Samsung Techwin SCP-3120VH Data Sheet
Samsung Techwin SCP-3120VH Data SheetSamsung Techwin SCP-3120VH Data Sheet
Samsung Techwin SCP-3120VH Data Sheet
 
Planificador de proyectos plantilla grupo 70
Planificador de proyectos plantilla grupo 70Planificador de proyectos plantilla grupo 70
Planificador de proyectos plantilla grupo 70
 

Similar to structure

CHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptxCHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptxGebruGetachew2
 
Structures in C.pptx
Structures in C.pptxStructures in C.pptx
Structures in C.pptxBoni Yeamin
 
slideset 7 structure and union (1).pdf
slideset 7 structure and union (1).pdfslideset 7 structure and union (1).pdf
slideset 7 structure and union (1).pdfHimanshuKansal22
 
Easy Understanding of Structure Union Typedef Enum in C Language.pdf
Easy Understanding of Structure Union Typedef Enum in C Language.pdfEasy Understanding of Structure Union Typedef Enum in C Language.pdf
Easy Understanding of Structure Union Typedef Enum in C Language.pdfsudhakargeruganti
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...ssuserd6b1fd
 
Pf cs102 programming-10 [structs]
Pf cs102 programming-10 [structs]Pf cs102 programming-10 [structs]
Pf cs102 programming-10 [structs]Abdullah khawar
 
data structure and c programing concepts
data structure and c programing conceptsdata structure and c programing concepts
data structure and c programing conceptskavitham66441
 

Similar to structure (20)

CHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptxCHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptx
 
Structures in C.pptx
Structures in C.pptxStructures in C.pptx
Structures in C.pptx
 
Ch7 structures
Ch7 structuresCh7 structures
Ch7 structures
 
Structures_Final_KLE (2).pptx
Structures_Final_KLE (2).pptxStructures_Final_KLE (2).pptx
Structures_Final_KLE (2).pptx
 
slideset 7 structure and union (1).pdf
slideset 7 structure and union (1).pdfslideset 7 structure and union (1).pdf
slideset 7 structure and union (1).pdf
 
lec14.pdf
lec14.pdflec14.pdf
lec14.pdf
 
Lab 13
Lab 13Lab 13
Lab 13
 
12Structures.pptx
12Structures.pptx12Structures.pptx
12Structures.pptx
 
Easy Understanding of Structure Union Typedef Enum in C Language.pdf
Easy Understanding of Structure Union Typedef Enum in C Language.pdfEasy Understanding of Structure Union Typedef Enum in C Language.pdf
Easy Understanding of Structure Union Typedef Enum in C Language.pdf
 
637225564198396290.pdf
637225564198396290.pdf637225564198396290.pdf
637225564198396290.pdf
 
Structures in C
Structures in CStructures in C
Structures in C
 
Chtp412
Chtp412Chtp412
Chtp412
 
structure.ppt
structure.pptstructure.ppt
structure.ppt
 
C++_notes.pdf
C++_notes.pdfC++_notes.pdf
C++_notes.pdf
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
 
structure1.pdf
structure1.pdfstructure1.pdf
structure1.pdf
 
Structures
StructuresStructures
Structures
 
C++11 - STL Additions
C++11 - STL AdditionsC++11 - STL Additions
C++11 - STL Additions
 
Pf cs102 programming-10 [structs]
Pf cs102 programming-10 [structs]Pf cs102 programming-10 [structs]
Pf cs102 programming-10 [structs]
 
data structure and c programing concepts
data structure and c programing conceptsdata structure and c programing concepts
data structure and c programing concepts
 

More from teach4uin

Master pages
Master pagesMaster pages
Master pagesteach4uin
 
.Net framework
.Net framework.Net framework
.Net frameworkteach4uin
 
Scripting languages
Scripting languagesScripting languages
Scripting languagesteach4uin
 
State management
State managementState management
State managementteach4uin
 
security configuration
security configurationsecurity configuration
security configurationteach4uin
 
static dynamic html tags
 static dynamic html tags static dynamic html tags
static dynamic html tagsteach4uin
 
static dynamic html tags
static dynamic html tagsstatic dynamic html tags
static dynamic html tagsteach4uin
 
New microsoft office power point presentation
New microsoft office power point presentationNew microsoft office power point presentation
New microsoft office power point presentationteach4uin
 
.Net overview
.Net overview.Net overview
.Net overviewteach4uin
 
Stdlib functions lesson
Stdlib functions lessonStdlib functions lesson
Stdlib functions lessonteach4uin
 
storage clas
storage classtorage clas
storage clasteach4uin
 

More from teach4uin (20)

Controls
ControlsControls
Controls
 
validation
validationvalidation
validation
 
validation
validationvalidation
validation
 
Master pages
Master pagesMaster pages
Master pages
 
.Net framework
.Net framework.Net framework
.Net framework
 
Scripting languages
Scripting languagesScripting languages
Scripting languages
 
Css1
Css1Css1
Css1
 
Code model
Code modelCode model
Code model
 
Asp db
Asp dbAsp db
Asp db
 
State management
State managementState management
State management
 
security configuration
security configurationsecurity configuration
security configuration
 
static dynamic html tags
 static dynamic html tags static dynamic html tags
static dynamic html tags
 
static dynamic html tags
static dynamic html tagsstatic dynamic html tags
static dynamic html tags
 
New microsoft office power point presentation
New microsoft office power point presentationNew microsoft office power point presentation
New microsoft office power point presentation
 
.Net overview
.Net overview.Net overview
.Net overview
 
Stdlib functions lesson
Stdlib functions lessonStdlib functions lesson
Stdlib functions lesson
 
enums
enumsenums
enums
 
memory
memorymemory
memory
 
array
arrayarray
array
 
storage clas
storage classtorage clas
storage clas
 

Recently uploaded

Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 

Recently uploaded (20)

Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 

structure

  • 1. Outline Introduction Structure Definitions Initializing Structures Accessing Members of Structures Using Structures with Functions Typedef Example: High-Performance Card Shuffling and Dealing Simulation Unions
  • 2.  Structures ◦ 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
  • 3.  Example struct card { char *face; char *suit; }; ◦ struct introduces the definition for structure card ◦ card is the structure name and is used to declare variables of the structure type ◦ card contains two members of type char * - face and suit
  • 4.  Struct information ◦ A struct cannot contain an instance of itself ◦ Can contain a member that is a pointer to the same structure type ◦ Structure definition does not reserve space in memory ◦ Creates a new data type that used to declare structure variables.  Declarations ◦ Declared like other variables: card oneCard, deck[ 52 ], *cPtr; ◦ Can use a comma separated list: struct card { char *face; char *suit; } oneCard, deck[ 52 ], *cPtr;
  • 5.  Valid Operations ◦ Assigning a structure to a structure of the same type ◦ Taking the address (&) of a structure ◦ Accessing the members of a structure ◦ Using the sizeof operator to determine the size of a structure
  • 6.  Initializer lists ◦ Example: card oneCard = { "Three", "Hearts" };  Assignment statements ◦ Example: card threeHearts = oneCard; ◦ Or: card threeHearts; threeHearts.face = “Three”; threeHearts.suit = “Hearts”;
  • 7.  Accessing structure members ◦ Dot operator (.) - use with structure variable name card myCard; printf( "%s", myCard.suit ); ◦ Arrow operator (->) - use with pointers to structure variables card *myCardPtr = &myCard; printf( "%s", myCardPtr->suit ); myCardPtr->suit equivalent to ( *myCardPtr ).suit
  • 8.  Passing structures to functions ◦ Pass entire structure  Or, pass individual members ◦ Both pass call by value  To pass structures call-by-reference ◦ Pass its address ◦ Pass reference to it  To pass arrays call-by-value ◦ Create a structure with the array as a member ◦ Pass the structure
  • 9.  typedef ◦ Creates synonyms (aliases) for previously defined data types ◦ Use typedef to create shorter type names. ◦ Example: typedef Card *CardPtr; ◦ Defines a new type name CardPtr as a synonym for type Card * ◦ typedef does not create a new data type  Only creates an alias
  • 10.  Pseudocode: ◦ Create an array of card structures ◦ Put cards in the deck ◦ Shuffle the deck ◦ Deal the cards
  • 11. 1. Load headers 1.1 Define struct 1.2 Function prototypes 1.3 Initialize deck[] and face[] 1.4 Initialize suit[] 1 /* Fig. 10.3: fig10_03.c 2 The card shuffling and dealing program using structures */ 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <time.h> 6 7 struct card { 8 const char *face; 9 const char *suit; 10 }; 11 12 typedef struct card Card; 13 14 void fillDeck( Card * const, const char *[], 15 const char *[] ); 16 void shuffle( Card * const ); 17 void deal( const Card * const ); 18 19 int main() 20 { 21 Card deck[ 52 ]; 22 const char *face[] = { "Ace", "Deuce", "Three", 23 "Four", "Five", 24 "Six", "Seven", "Eight", 25 "Nine", "Ten", 26 "Jack", "Queen", "King"}; 27 const char *suit[] = { "Hearts", "Diamonds", 28 "Clubs", "Spades"}; 29 30 srand( time( NULL ) );
  • 12. 2. Randomize 2. fillDeck 2.1 shuffle 2.2 deal 3. Function definitions 31 32 fillDeck( deck, face, suit ); 33 shuffle( deck ); 34 deal( deck ); 35 return 0; 36 } 37 38 void fillDeck( Card * const wDeck, const char * wFace[], 39 const char * wSuit[] ) 40 { 41 int i; 42 43 for ( i = 0; i <= 51; i++ ) { 44 wDeck[ i ].face = wFace[ i % 13 ]; 45 wDeck[ i ].suit = wSuit[ i / 13 ]; 46 } 47 } 48 49 void shuffle( Card * const wDeck ) 50 { 51 int i, j; 52 Card temp; 53 54 for ( i = 0; i <= 51; i++ ) { 55 j = rand() % 52; 56 temp = wDeck[ i ]; 57 wDeck[ i ] = wDeck[ j ]; 58 wDeck[ j ] = temp; 59 } 60 } Put all 52 cards in the deck. face and suit determined by remainder (modulus). Select random number between 0 and 51. Swap element i with that element.
  • 13. 3. Function definitions 61 62 void deal( const Card * const wDeck ) 63 { 64 int i; 65 66 for ( i = 0; i <= 51; i++ ) 67 printf( "%5s of %-8s%c", wDeck[ i ].face, 68 wDeck[ i ].suit, 69 ( i + 1 ) % 2 ? 't' : 'n' ); 70 } Cycle through array and print out data.
  • 14. Program Output Eight of Diamonds Ace of Hearts Eight of Clubs Five of Spades Seven of Hearts Deuce of Diamonds Ace of Clubs Ten of Diamonds Deuce of Spades Six of Diamonds Seven of Spades Deuce of Clubs Jack of Clubs Ten of Spades King of Hearts Jack of Diamonds Three of Hearts Three of Diamonds Three of Clubs Nine of Clubs Ten of Hearts Deuce of Hearts Ten of Clubs Seven of Diamonds Six of Clubs Queen of Spades Six of Hearts Three of Spades Nine of Diamonds Ace of Diamonds Jack of Spades Five of Clubs King of Diamonds Seven of Clubs Nine of Spades Four of Hearts Six of Spades Eight of Spades Queen of Diamonds Five of Diamonds Ace of Spades Nine of Hearts King of Clubs Five of Hearts King of Spades Four of Diamonds Queen of Hearts Eight of Hearts Four of Spades Jack of Hearts Four of Clubs Queen of Clubs
  • 15.  union ◦ Memory that contains a variety of objects over time ◦ Only contains one data member at a time ◦ Members of a union share space ◦ Conserves storage ◦ Only the last data member defined can be accessed  union declarations ◦ Same as struct union Number { int x; float y; }; Union myObject;
  • 16.  Valid union operations ◦ Assignment to union of same type: = ◦ Taking address: & ◦ Accessing union members: . ◦ Accessing members using pointers: ->
  • 17. 1. Define union 1.1 Initialize variables 2. Set variables 3. Print 1 /* Fig. 10.5: fig10_05.c 2 An example of a union */ 3 #include <stdio.h> 4 5 union number { 6 int x; 7 double y; 8 }; 9 10 int main() 11 { 12 union number value; 13 14 value.x = 100; 15 printf( "%sn%sn%s%dn%s%fnn", 16 "Put a value in the integer member", 17 "and print both members.", 18 "int: ", value.x, 19 "double:n", value.y ); 20 21 value.y = 100.0; 22 printf( "%sn%sn%s%dn%s%fn", 23 "Put a value in the floating member", 24 "and print both members.", 25 "int: ", value.x, 26 "double:n", value.y ); 27 return 0; 28 }
  • 18. Program Output Put a value in the integer member and print both members. int: 100 double: -92559592117433136000000000000000000000000000000000000000000000.00000 Put a value in the floating member and print both members. int: 0 double: 100.000000
  • 19. Program Output 1 January 2 February 3 March 4 April 5 May 6 June 7 July 8 August 9 September 10 October 11 November 12 December