Title: Data Structures and Abstract Data Types
1Data Structures and Abstract Data Types
2Chapter Contents
- 3.1 Data Structures, Abstract Data Types and
Implementations - 3.2 Static Arrays
- 3.3 Multidimensional Arrays
- 3.4 Dynamic Arrays
3Data Structures, Abstract Data Types, and
Implementations
- Recall ADT is a mathematical model of a set of
data items and operations on the data items. - Implementation consists of
- Storage (data) structures
- Algorithms for basic operations
- Note the following figure
- C provides large collection of data types and
structures
4C Types
5ADT and Data Structure
- Typical ADTs
- Lists, Stacks, Queues, Sets, Maps, Graphs and
Priority Queues - Typical data structures
- Static (Fixed) Arrays, Dynamic (Resizing)
Arrays, Linked Lists, Linked Trees, Array-Based
Trees, Balanced Binary Trees, Hash Tables,
Adjacency Lists (Graphs), Adjacency Matrices
(Graphs)
6Arrays
- Collection of data elements
- All of same type
- Each accessed by specifying position
- Static array
- Compiler determines how memory allocated
- Dynamic array
- Allocation takes place at run time (execution)
7Single Dimension Arrays
- Syntax ElementType arrayName CAPACITY Elemen
tType arrayName CAPACITY
initializer_list - Example int b 10
- Elements accessed by
- name and operation b5
8Character Arrays
- Elements of an array may be of any type
- Including characters
- Example char name NAME_CAPACITY "John
Doe" - If array initialized shorter than array capacity
- extra locations filled with null character
- (end-of-string mark)
9Subscript Operation
- We have said elements accessed by name and
a5 - Consider the to be an operator
- The subscript operator
- Performs address translation
- Name of the array is a pointer constant
- The base address
10Pointers and Arrays
- The name of an array is synonymous with a pointer
to the memory location of the first element in
the array. - a is a constant pointer to the first element in
the array - The use of a in a program will be evaluated to
a0
11Example
- int sum(int ary, int length)
-
- int i0, total0
- for (i0 iltlength i)
- total aryi
- return total
-
12Example (conts)
- int sum(int ary, int length)
-
- int i0, total0
- for (i0 iltlength i)
- total (ary i)
- return total
13Example (conts)
- include ltiostreamgt
- using namespace std
- int main()
-
- int total, x 1,2,3,4
- total sum(x,4)
- cout ltlt total ltlt total
- return 0
-
14Using Arrays
- Accessing array for output
- See Fig 3.3
- Accessing array for input from keyboard
- See Fig. 3.4
- Note use of arrays as parameters
- Must specify separately number of elements of
array being used (capacity)
15Out of Range Errors
- Most C compilers do not by default check
indices for out of range - Results of out of range array access
- Program can give weird results
- Note example, Fig. 3.5
- Solution use structured type vector in STL or
check by programmer coding
16Problems with C-Style Arrays
- Capacity cannot change.
- An array is not an object
- (in the OOP sense)
- The Deeper Problem
- C-style arrays aren't self-contained
- Data, functions, and size not encapsulated
17Multidimensional Arrays
- Consider a table of test scores for several
different students - Two-dimensional array
- Syntax ElementType arrayName numRowsnumCols
18Multidimensional Arrays
- Consider multiple pages of the student grade
bookconst int NUM_ROWS 30, NUM_COLS 5,
NUM_RANKS 10typedef double
ThreeDimArrayNUM_ROWSNUM_COLSNUM_RANKS
. . .
19Array of Array Declarations
- An array of arrays
- An array whose elements are other arrays
20Array of Array Declarations
- Each of the rows is itself a one dimensional
array of values
21Memory Allocation in 2-Dimensional Arrays
- Elements stored in rowwise order
- Also called column major order
location 04 is followed in memory by location
10
22Dynamic Arrays
- Recall earlier mention of arrays with fixed size
at compile time - Space wasted by unused elements
- Program cannot adjust if size is set too small
- Dynamic (run time) allocation mechanism provided
- Acquire memory as needed
- Release memory when no longer needed
- C commands
- new and delete
23A model of Computer Memory
Variables that persist in memory throughout the
execution of the program
dynamically allocated memory is stored on the
free store (heap)
Variables declared in the functions, the copy of,
or a reference to, the parameters that are being
passed to the functions, etc.
24The new Operator
- Syntax for arraysnew Type capacity
- This command issues a run-time request for a
block of memory - Asks for enough memory for the specified number
of elements of the stated type - Exampleint arrayPtrarrayPtr new int6
25Pointer Arithmetic
- Possible to alter pointer contents
- The pointer is a variable
- It is not a pointer constant like an array name
- Example Given
- Then ptr
26Failures of new
- When new execute
- Requests memory from heap(free store)
- Allocates that block to executing program
- Possible to use up available heap memory
- If not enough memory for request, new throws an
exception bad_alloc - Possible to use try and catch mechanism to take
appropriate action when exception occurs
27Failures of new
- Use
- new(nothrow) type
- new(nothrow) typecapacity
- it will return a null pointer if memory can not
be allocated. (instead of throw a exception)
28The delete Operation
- Counterpart to the new operation
- Requests memory be returned to the heap
- Can then be reused by later allocations
- Syntaxdelete pointerVariabledelete
arrayPointerVariable - Frees the dynamically memory whose address is
stored in the variable - Does not delete the variable
29The delete Operation
- Int intPtr new int
- Delele intPtr
- make the memory available for later use. Now
intPtr is a dangling pointer. You cannot
dereference a dangling pointer. - Solution
- Delele intPtr
- intPtr 0
30The delete Operation
- Then, we can safely deference a pointer by,
- if (intPtr !0)
- // ok, it can be safely dereferenced
- else
- // not ok, print message intPtrs memory has
been deallocated
31Memory Leaks
- Important for programmer to make sure to
deallocate memory originally allocated by new - What if new is called again for intPtr? (no
deallocation before the re-usage) - Originally allocated memory now cannot be
accessed, nor is it available for reallocation - The memory to which a pointer points should
always be deallocated before the pointer is
assigned a new address
32Aggregate Data Types
- Predefined types not always adequate to model the
problem - When objects have multiple attributes
- When objects have collections of non-homogeneous
elements - C provides structs and classes
- Create new types with multiple attributes
33Structures
- Characteristics
- has a fixed size
- is ordered
- elements may be of different size
- direct access of elements by name (not index)
- struct Date int month, day, yearchar
dayOfWeek 7
34FAQs about Structures
- structs can be nested (can contain struct
objects) - Access members with
- name of struct object
- dot (member selector operator) .
- name of struct member
- Date today 3, 4, 2005, "Tuesday")
- cout ltlt today.month
35Pointers to Structs
- Pointers can be bound to any typeDate today
3, 4, 2005, "Tuesday") Date datePtr today - Use for accessing the original locationcout ltlt
(datePtr).daycout ltlt datePtr -gt day
//(simpler notation)
36Reading Assignment