/** * int-vector.c * An implementation of "vectors" - Slightly safer arrays. */ // +---------+-------------------------------------------------------- // | Headers | // +---------+ #include #include #include #include "int-vector.h" // +-------+---------------------------------------------------------- // | Types | // +-------+ struct int_vector { int *values; int size; }; // +-----------+------------------------------------------------------ // | Functions | // +-----------+ struct int_vector * iv_new (int size) { struct int_vector *iv = malloc (sizeof (struct int_vector)); if (iv == NULL) return NULL; iv->size = size; iv->values = malloc (size * sizeof (int)); if (iv->values == NULL) { free (iv); return NULL; } return iv; } // iv_new int iv_get (struct int_vector *iv, int i) { if (iv == NULL) { fprintf (stderr, "Cannot get values from null vector.\n"); return INT_MIN; } else if (i < 0) { fprintf (stderr, "Cannot use negative indices (%d)\n", i); return INT_MIN; } else if (i >= iv->size) { fprintf (stderr, "Index %d is not in the range [0,%d)\n", i, iv->size); return INT_MIN; } return iv->values[i]; } // iv_get void iv_set (struct int_vector *iv, int i, int v) { if (iv == NULL) { fprintf (stderr, "Cannot set values from null vector.\n"); } else if (i < 0) { fprintf (stderr, "Cannot use negative indices (%d)\n", i); } else if (i >= iv->size) { fprintf (stderr, "Index %d is not in the range [0,%d)\n", i, iv->size); } else iv->values[i] = v; } // iv_set int iv_size (struct int_vector *iv) { if (iv == NULL) return 0; else return iv->size; } // iv_size