-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathintv.c
86 lines (70 loc) · 1.4 KB
/
intv.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include "intv.h"
/*
* Add an integer to an integer vector (or create a new vector if intv is NULL).
*
* Return a pointer to a possibly relocated intv, or exit on error.
*/
int **
addint(int **intv, int num)
{
int i;
/* find first empty slot */
for (i = 0; intv != NULL && intv[i] != NULL; i++)
;
/* ensure enough space */
intv = reallocarray(intv, i + 2, sizeof(int *));
if (intv == NULL)
err(1, "%s: reallocarray", __func__);
intv[i] = malloc(sizeof(num));
if (intv[i] == NULL)
err(1, "%s: malloc", __func__);
*intv[i] = num;
intv[i+1] = NULL;
return intv;
}
/* Clear and free a number vector. */
void
clrintv(int ***intv)
{
int i;
if (*intv == NULL)
return;
/* free up individual numbers first. */
for (i = 0; (*intv)[i] != NULL; i++) {
free((*intv)[i]);
(*intv)[i] = NULL;
}
free(*intv);
*intv = NULL;
}
/*
* Duplicate a number vector.
*
* Return the newly allocated vector on success, NULL if intv is NULL and exit
* on error.
*/
int **
dupintv(int **intv)
{
int i;
int **r = NULL;
if (intv == NULL)
return NULL;
for (i = 0; intv[i]; i++)
r = addint(r, *intv[i]);
return r;
}
/* Print a null terminated number vector on the designated stream. */
void
fprintintv(FILE *fp, int **intv)
{
while (intv && *intv)
fprintf(fp, " %d", **intv++);
fprintf(fp, "\n");
}
/* Print a null terminated number vector. */
void
printintv(int **intv)
{
fprintintv(stdout, intv);
}