home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
World of Shareware - Software Farm 2
/
wosw_2.zip
/
wosw_2
/
CPROG
/
CGAZV5N3.ZIP
/
ARRAY.C
< prev
next >
Wrap
C/C++ Source or Header
|
1991-03-02
|
2KB
|
48 lines
/******** Listing 2 *********************** ARRAY.C ******
* ARRAY.C : Implementation of dynamic array in C
* See Listing 1 for copyright terms.
********************************************************/
#include "array.h"
#include <stdio.h>
/* an error handler which can only be seen within this file: */
static void error(char * msg) {
fprintf(stderr, "dynamic_array error: %s\n", msg);
exit(1);
}
/* Call to initialize a dynamic array on the stack: */
void create_array(dynamic_array* da, size_t sz) {
/* initialize the elements of the structure: */
da->size = sz;
/* calloc creates sz items of size int and
initializes each to 0 */
da->vec = calloc(sz, sizeof(int));
if(da->vec == NULL) error("out of memory in create_array");
}
/* Special function to call when creating a dynamic array on the heap: */
dynamic_array* make_heap_array(size_t sz) {
/* first, create memory to hold the structure: */
dynamic_array* da = malloc(sizeof(dynamic_array));
if(da == NULL) error("out of memory in make_heap_array");
/* then make and initialize the array elements themselves: */
create_array(da, sz);
return da;
}
/* call to clean up a dynamic array on the stack: */
void free_array(dynamic_array* da) {
free(da->vec); /* free memory held in struct */
}
/* Special function to call when releasing a dynamic array from the heap: */
void release_heap_array(dynamic_array* da) {
free_array(da);
free(da); /* free memory used for struct */
}
int* value(dynamic_array* da, int index) {
if(index < 0 || index >= da->size) error("index out of range");
return &(da->vec[index]);
}