I. Friday Problems with C Structs and Pointer A. vectors ------------------------------------------ VECTORS: ARRAYS WITH LENGTHS Want to combine an array with its size, for: - convenience - bounds checking However, still want to be able to: - pass it efficiently to functions, - access elements in constant time ------------------------------------------ How should we do this? 1. operations ------------------------------------------ WHAT OPERATIONS TO HAVE ON VECTORS? ------------------------------------------ What functions should we build for clients? 2. tests ------------------------------------------ TESTS FOR VECTOR #include "tap.h" #include "vector.h" int main() { plan(5); vector vec5 = mkvec(0.0, 5); ok(vec_size(vec5) == 5, "vec_size(vec5) == 5"); ok(vec_get(vec5, 0) == 0.0, "vec_get(vec5, 0) == 0.0"); ok(vec_get(vec5, 2) == 0.0, "vec_get(vec5, 2) == 0.0"); ok(vec_get(vec5, 4) == 0.0, "vec_get(vec5, 4) == 0.0"); vec_set(vec5, 3, 3.14); ok(vec_get(vec5, 3) == 3.14, "vec_get(vec5, 3) == 3.14"); return exit_status(); } ------------------------------------------ 3. data structure ------------------------------------------ WHAT DATA STRUCTURE TO USE? #ifndef VECTOR_H #define VECTOR_H 1 /* ... extern decls for functions ...*/ #endif ------------------------------------------ 4. operations a. creation and initialization ------------------------------------------ CREATION AND INITIALIZATION /* requires: sz > 0 * ensures: result is a vector with the given size, * all of whose elements are initialized to val */ vector mkvec(ELEM val, int sz) { ------------------------------------------ b. size ------------------------------------------ // requires: v is allocated (and not NULL) // ensures: result is the size of v; int vec_size(vector v) { } ------------------------------------------ c. element access and assignment ------------------------------------------ ELEMENT ACCESS AND ASSIGNMENT // requires: v is allocated (and not NULL) // requires: 0 <= i && i < vec_size(v) // ensures: result is the element at index i extern ELEM vec_get(vector v, int i) { // requires: v is allocated (and not NULL) // requires: 0 <= i && i < vec_size(v) // modifies: the element of v at index i // ensures: the element at index i becomes val extern void vec_set(vector v, int i, ELEM val) { ------------------------------------------ 5. extensions How could we do bounds checking on access and assignment? Could we write a function to do the equivalent of a for loop? How could we make it so vectors could grow and shrink at runtime?