SlideShare a Scribd company logo
1 of 32
Download to read offline
Pointers In Real Life
Peter Thedens and Landon Woerdeman
Problem
A professor has an unsorted text file containing student “netid”s and scores.
The professor wants the data to be ordered both alphabetically and by score.
Additionally, the professor wants to know the top scorer(s) and the mean and median
score.
Goal of program
● Read a file containing students’ grades
● Sort grades by username and score (and output)
● Find top scoring student(s) (and output)
● Compute mean and median (and output)
grades.txt
nportman, 83
thanks, 73
mdamon, 100
sstallone, 67
bpitt, 83
ajolie, 75
tcruise, 75
jfranco, 30
jdepp, 82
ldicaprio, 95
jlawrence, 97
sjohansson, 88
mkunis, 93
dwashington, 78
cbale, 47
Process
Read user input Read and parse file
Sort data Calculations
Output file
Read input
Processing
Process
Read user input Read and parse file
Sort data Calculations
Output file
Read input
Processing
Read User input
● Command line arguments
○ Consists of an array of C-strings (argv) and a number (argc)
○ argc – Number of strings
○ argv – C-strings contain each command line argument
○ Note: argv[0] contains the name of the program
● fopen() for reading from file
○ Takes a file path and returns a file pointer
○ Returns NULL if file does not exist
○ “r” specifies read operation
Grades structure
● Using structs, we can create a grade
● More on structs here
○ Access members with ‘.’
○ grade1.score returns the user’s score
● Basically a holder containing:
○ int score - integer containing student’s score
○ char* netid - C-string containing netid
■ Character pointer
■ Holds the address of the first character in the string
Process
Read user input Read and parse file
Sort data Calculations
Output file
Read input
Processing
Read and parse data loop
while(not end of file)
Get line of input
Parse line of input
Add initial loop
● Initially don’t know number of entries
● Can’t allocate correct space
● To fix, iterate twice
○ Loop 1: Count entries
○ Allocate space using malloc()
○ Loop 2: Parse entries
Read and parse data (revised)
while(not end of file)
Get line of input
Parse line of input
while(not end of file)
Increment count
Allocate
Read and parse data (revised)
while(not end of file)
Get line of input
Parse line of input
while(not end of file)
Increment count
Allocate
Counting lines of file
● We will use getLine() to read file
● This returns -1 when end of file is reached
● Increment counter until -1 is returned
Read and parse data (revised)
while(not end of file)
Get line of input
Parse line of input
while(not end of file)
Increment count
Allocate
Memory allocation
● Use malloc() to reserve space for array of grades
● Discussed under advanced topics here
● Does 2 things
○ Reserves desired amount of memory
○ Returns pointer to that memory
Read and parse data (revised)
while(not end of file)
Get line of input
Parse line of input
while(not end of file)
Increment count
Allocate
Read line of input
● Call getLine() (described here)
○ Pass file pointer, character pointer (for string), and size pointer
○ Updates passed character pointer to read string
○ Updates size pointer to size of string (disregarded)
Read and parse data (revised)
while(not end of file)
Get line of input
Parse line of input
while(not end of file)
Increment count
Allocate
Parsing
● Parse string
● First part: netid
○ Use strsep() to separate the string based on the comma
○ Described here
○ Assign to grades[i].netid a character pointer to the string (returned by strsep())
○ For our use, the pointer must be set to NULL before getting the line
● Second part: score
○ Use atoi() (described here) to parse an integer from a string
○ Assign to grades[i].score the score of element of the array grades
Parsing code snippet
Process
Read user input Read and parse file
Sort data Calculations
Output file
Read input
Processing
Sort data
● We will use a selection sort (described here)
○ Search through the unsorted part of array
○ Find minimum element and swap with first element
■ Using pointers to swap is described here
○ Decrease size of unsorted part of array
● To sort netids, we will use strcmp() to identify smallest element
○ If the return value of strcmp() is negative, first parameter is smaller
○ If the return value of strcmp() is positive, second parameter is smaller
○ strcmp() is described here
● To sort scores, we will use ‘<’ to identify smallest element
Sorting code snippet
Process
Read user input Read and parse file
Sort data Calculations
Output file
Read input
Processing
Calculations
● Median
○ Use sorted-by-score array
○ If number of scores is odd, use middle element
○ If number of scores is even, use average of middle 2 elements
● Mean
○ Add up total of scores in array and divide by number of elements
● Top scorer(s)
○ Find highest score (end of sorted array)
○ Iterate backwards until score is less than highest
○ From this index to the end are the top scorers
Calculations code snippet
Process
Read user input Read and parse file
Sort data Calculations
Output file
Read input
Processing
Output file
● At each step, the output file is being created
○ After each sort and calculations print
○ fprintf() is described here
○ Is like printf to a file rather than the console
● File pointer is closed at termination of program
○ fclose() writes the file
Output code snippet
Example output
Why are pointers needed?
● File pointer
● Dynamic memory allocation
● Swap function
For more on pointers: http://cpointers.weebly.com

More Related Content

What's hot

Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)swapnac12
 
Chapter1 Formal Language and Automata Theory
Chapter1 Formal Language and Automata TheoryChapter1 Formal Language and Automata Theory
Chapter1 Formal Language and Automata TheoryTsegazeab Asgedom
 
sparse matrix in data structure
sparse matrix in data structuresparse matrix in data structure
sparse matrix in data structureMAHALAKSHMI P
 
OOPS with C++ | Concepts of OOPS | Introduction
OOPS with C++ | Concepts of OOPS | IntroductionOOPS with C++ | Concepts of OOPS | Introduction
OOPS with C++ | Concepts of OOPS | IntroductionADITYATANDONKECCSE
 
Push Down Automata (PDA) | TOC (Theory of Computation) | NPDA | DPDA
Push Down Automata (PDA) | TOC  (Theory of Computation) | NPDA | DPDAPush Down Automata (PDA) | TOC  (Theory of Computation) | NPDA | DPDA
Push Down Automata (PDA) | TOC (Theory of Computation) | NPDA | DPDAAshish Duggal
 
Informed and Uninformed search Strategies
Informed and Uninformed search StrategiesInformed and Uninformed search Strategies
Informed and Uninformed search StrategiesAmey Kerkar
 
Deep Learning for Natural Language Processing: Word Embeddings
Deep Learning for Natural Language Processing: Word EmbeddingsDeep Learning for Natural Language Processing: Word Embeddings
Deep Learning for Natural Language Processing: Word EmbeddingsRoelof Pieters
 
Lexical Analysis - Compiler Design
Lexical Analysis - Compiler DesignLexical Analysis - Compiler Design
Lexical Analysis - Compiler DesignAkhil Kaushik
 
data structure(tree operations)
data structure(tree operations)data structure(tree operations)
data structure(tree operations)Waheed Khalid
 
State space search and Problem Solving techniques
State space search and Problem Solving techniquesState space search and Problem Solving techniques
State space search and Problem Solving techniquesKirti Verma
 
Cs2303 theory of computation all anna University question papers
Cs2303 theory of computation all anna University question papersCs2303 theory of computation all anna University question papers
Cs2303 theory of computation all anna University question papersappasami
 
Finite Automata in compiler design
Finite Automata in compiler designFinite Automata in compiler design
Finite Automata in compiler designRiazul Islam
 
AI_Session 10 Local search in continious space.pptx
AI_Session 10 Local search in continious space.pptxAI_Session 10 Local search in continious space.pptx
AI_Session 10 Local search in continious space.pptxAsst.prof M.Gokilavani
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in pythonTMARAGATHAM
 

What's hot (20)

Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)
 
6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx
 
Chapter1 Formal Language and Automata Theory
Chapter1 Formal Language and Automata TheoryChapter1 Formal Language and Automata Theory
Chapter1 Formal Language and Automata Theory
 
sparse matrix in data structure
sparse matrix in data structuresparse matrix in data structure
sparse matrix in data structure
 
OOPS with C++ | Concepts of OOPS | Introduction
OOPS with C++ | Concepts of OOPS | IntroductionOOPS with C++ | Concepts of OOPS | Introduction
OOPS with C++ | Concepts of OOPS | Introduction
 
Symbol Table
Symbol TableSymbol Table
Symbol Table
 
Push Down Automata (PDA) | TOC (Theory of Computation) | NPDA | DPDA
Push Down Automata (PDA) | TOC  (Theory of Computation) | NPDA | DPDAPush Down Automata (PDA) | TOC  (Theory of Computation) | NPDA | DPDA
Push Down Automata (PDA) | TOC (Theory of Computation) | NPDA | DPDA
 
Heuristic search
Heuristic searchHeuristic search
Heuristic search
 
Informed and Uninformed search Strategies
Informed and Uninformed search StrategiesInformed and Uninformed search Strategies
Informed and Uninformed search Strategies
 
Pointers
PointersPointers
Pointers
 
Deep Learning for Natural Language Processing: Word Embeddings
Deep Learning for Natural Language Processing: Word EmbeddingsDeep Learning for Natural Language Processing: Word Embeddings
Deep Learning for Natural Language Processing: Word Embeddings
 
Lexical Analysis - Compiler Design
Lexical Analysis - Compiler DesignLexical Analysis - Compiler Design
Lexical Analysis - Compiler Design
 
data structure(tree operations)
data structure(tree operations)data structure(tree operations)
data structure(tree operations)
 
Chapter 4 strings
Chapter 4 stringsChapter 4 strings
Chapter 4 strings
 
OOPS Characteristics
OOPS CharacteristicsOOPS Characteristics
OOPS Characteristics
 
State space search and Problem Solving techniques
State space search and Problem Solving techniquesState space search and Problem Solving techniques
State space search and Problem Solving techniques
 
Cs2303 theory of computation all anna University question papers
Cs2303 theory of computation all anna University question papersCs2303 theory of computation all anna University question papers
Cs2303 theory of computation all anna University question papers
 
Finite Automata in compiler design
Finite Automata in compiler designFinite Automata in compiler design
Finite Automata in compiler design
 
AI_Session 10 Local search in continious space.pptx
AI_Session 10 Local search in continious space.pptxAI_Session 10 Local search in continious space.pptx
AI_Session 10 Local search in continious space.pptx
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 

Similar to Pointers in real life

Similar to Pointers in real life (20)

Algorithms.
Algorithms. Algorithms.
Algorithms.
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Algorithm By AMT.pptx
Algorithm By AMT.pptxAlgorithm By AMT.pptx
Algorithm By AMT.pptx
 
Tri Merge Sorting Algorithm
Tri Merge Sorting AlgorithmTri Merge Sorting Algorithm
Tri Merge Sorting Algorithm
 
CS3114_09212011.ppt
CS3114_09212011.pptCS3114_09212011.ppt
CS3114_09212011.ppt
 
Python bible
Python biblePython bible
Python bible
 
Cis435 week04
Cis435 week04Cis435 week04
Cis435 week04
 
Cis435 week06
Cis435 week06Cis435 week06
Cis435 week06
 
R programming slides
R  programming slidesR  programming slides
R programming slides
 
data structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysoredata structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysore
 
DSA
DSADSA
DSA
 
Data Structures 6
Data Structures 6Data Structures 6
Data Structures 6
 
Searching Algorithms
Searching AlgorithmsSearching Algorithms
Searching Algorithms
 
Unit7
Unit7Unit7
Unit7
 
Data structure
Data structureData structure
Data structure
 
ds 1 Introduction to Data Structures.ppt
ds 1 Introduction to Data Structures.pptds 1 Introduction to Data Structures.ppt
ds 1 Introduction to Data Structures.ppt
 
Data structure Unit-I Part A
Data structure Unit-I Part AData structure Unit-I Part A
Data structure Unit-I Part A
 
Iare ds ppt_3
Iare ds ppt_3Iare ds ppt_3
Iare ds ppt_3
 
jn;lm;lkm';m';;lmppt of data structure.pdf
jn;lm;lkm';m';;lmppt of data structure.pdfjn;lm;lkm';m';;lmppt of data structure.pdf
jn;lm;lkm';m';;lmppt of data structure.pdf
 
Algorithms
Algorithms Algorithms
Algorithms
 

Recently uploaded

Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 

Recently uploaded (20)

Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 

Pointers in real life

  • 1. Pointers In Real Life Peter Thedens and Landon Woerdeman
  • 2. Problem A professor has an unsorted text file containing student “netid”s and scores. The professor wants the data to be ordered both alphabetically and by score. Additionally, the professor wants to know the top scorer(s) and the mean and median score.
  • 3. Goal of program ● Read a file containing students’ grades ● Sort grades by username and score (and output) ● Find top scoring student(s) (and output) ● Compute mean and median (and output)
  • 4. grades.txt nportman, 83 thanks, 73 mdamon, 100 sstallone, 67 bpitt, 83 ajolie, 75 tcruise, 75 jfranco, 30 jdepp, 82 ldicaprio, 95 jlawrence, 97 sjohansson, 88 mkunis, 93 dwashington, 78 cbale, 47
  • 5. Process Read user input Read and parse file Sort data Calculations Output file Read input Processing
  • 6. Process Read user input Read and parse file Sort data Calculations Output file Read input Processing
  • 7. Read User input ● Command line arguments ○ Consists of an array of C-strings (argv) and a number (argc) ○ argc – Number of strings ○ argv – C-strings contain each command line argument ○ Note: argv[0] contains the name of the program ● fopen() for reading from file ○ Takes a file path and returns a file pointer ○ Returns NULL if file does not exist ○ “r” specifies read operation
  • 8. Grades structure ● Using structs, we can create a grade ● More on structs here ○ Access members with ‘.’ ○ grade1.score returns the user’s score ● Basically a holder containing: ○ int score - integer containing student’s score ○ char* netid - C-string containing netid ■ Character pointer ■ Holds the address of the first character in the string
  • 9. Process Read user input Read and parse file Sort data Calculations Output file Read input Processing
  • 10. Read and parse data loop while(not end of file) Get line of input Parse line of input
  • 11. Add initial loop ● Initially don’t know number of entries ● Can’t allocate correct space ● To fix, iterate twice ○ Loop 1: Count entries ○ Allocate space using malloc() ○ Loop 2: Parse entries
  • 12. Read and parse data (revised) while(not end of file) Get line of input Parse line of input while(not end of file) Increment count Allocate
  • 13. Read and parse data (revised) while(not end of file) Get line of input Parse line of input while(not end of file) Increment count Allocate
  • 14. Counting lines of file ● We will use getLine() to read file ● This returns -1 when end of file is reached ● Increment counter until -1 is returned
  • 15. Read and parse data (revised) while(not end of file) Get line of input Parse line of input while(not end of file) Increment count Allocate
  • 16. Memory allocation ● Use malloc() to reserve space for array of grades ● Discussed under advanced topics here ● Does 2 things ○ Reserves desired amount of memory ○ Returns pointer to that memory
  • 17. Read and parse data (revised) while(not end of file) Get line of input Parse line of input while(not end of file) Increment count Allocate
  • 18. Read line of input ● Call getLine() (described here) ○ Pass file pointer, character pointer (for string), and size pointer ○ Updates passed character pointer to read string ○ Updates size pointer to size of string (disregarded)
  • 19. Read and parse data (revised) while(not end of file) Get line of input Parse line of input while(not end of file) Increment count Allocate
  • 20. Parsing ● Parse string ● First part: netid ○ Use strsep() to separate the string based on the comma ○ Described here ○ Assign to grades[i].netid a character pointer to the string (returned by strsep()) ○ For our use, the pointer must be set to NULL before getting the line ● Second part: score ○ Use atoi() (described here) to parse an integer from a string ○ Assign to grades[i].score the score of element of the array grades
  • 22. Process Read user input Read and parse file Sort data Calculations Output file Read input Processing
  • 23. Sort data ● We will use a selection sort (described here) ○ Search through the unsorted part of array ○ Find minimum element and swap with first element ■ Using pointers to swap is described here ○ Decrease size of unsorted part of array ● To sort netids, we will use strcmp() to identify smallest element ○ If the return value of strcmp() is negative, first parameter is smaller ○ If the return value of strcmp() is positive, second parameter is smaller ○ strcmp() is described here ● To sort scores, we will use ‘<’ to identify smallest element
  • 25. Process Read user input Read and parse file Sort data Calculations Output file Read input Processing
  • 26. Calculations ● Median ○ Use sorted-by-score array ○ If number of scores is odd, use middle element ○ If number of scores is even, use average of middle 2 elements ● Mean ○ Add up total of scores in array and divide by number of elements ● Top scorer(s) ○ Find highest score (end of sorted array) ○ Iterate backwards until score is less than highest ○ From this index to the end are the top scorers
  • 28. Process Read user input Read and parse file Sort data Calculations Output file Read input Processing
  • 29. Output file ● At each step, the output file is being created ○ After each sort and calculations print ○ fprintf() is described here ○ Is like printf to a file rather than the console ● File pointer is closed at termination of program ○ fclose() writes the file
  • 32. Why are pointers needed? ● File pointer ● Dynamic memory allocation ● Swap function For more on pointers: http://cpointers.weebly.com