Assignment 2
Contents: | Arrays, dynamic memory and pointers. |
Preparations: |
Net lesson 3 |
Examination: | Orally in the computer lab no later than November 30, 2020. |
You should write a program that reads words from standard input, stores and count their frequencies.
Sample output:
include 4
string 1
h 4
stdio 1
stdlib 1
ctype 1
typedef 1
struct 2
Node 4
char 9
word 5
int 8
(It looks as if a program text has been used as input.)
Work flow
-
Write a function
char *readWord()
that reads a word from standard input, stores it in a dynamically allocated area and returns a pointer to it.A word starts with a letter followed by by letters and/or digits. All other characters terminate words and can not be a part of a word.
- Create a local array with 100 characters.
-
Read characters until a letter is found.
That letter is the first in the word.
ReturnNULL
if no letter is found before EOF. - Continue to read and store characters until the first one that is not a letter or digit is found.
-
Allocate an area of suitable size (
malloc
) and move the read word to it. - Return a pointer to the area.
-
Create two global (i.e. declared outside all functions) arrays
words
for holding words andfreq
for holding frequencies. You need also an integerused
telling the number of stored words which, of course should be set to 0 from the beginning. -
Write a function
count(char *word)
that searches the arraywords
. If the word is found, its frequency should be updated. If the word is not found, it should be stored in the first free position (used
) and the corresponding frequency should be set to 1. - Test with your program as input.