blob: e9aec190e8a471baab9b41453063c785072b6f97 (
plain)
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
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
int length;
char *line;
} sNode;
struct String
{
int index;
int size;
sNode *arr;
};
struct String *string_new(char *str);
void string_append(struct String *a, char *b);
void string_resize(struct String *s);
struct String *string_new(char *str)
{
struct String *ret = (struct String *) calloc(1, sizeof(struct String));
ret->arr = (sNode *) calloc(1, (sizeof(sNode) * 200));
ret->size = 200;
string_append(ret, str);
return ret;
}
void string_append(struct String *a, char *b)
{
if ((a->size-1) == a->index)
string_resize(a);
a->arr[a->index].line = b;
a->arr[a->index].length = strlen(b);
a->index++;
}
void string_resize(struct String *s)
{
/* quadruple the size */
int newSize = s->size * 4;
printf("debug: resizing to new size of %d\n", newSize);
s->size = newSize;
sNode *newarr = (sNode *) realloc(s->arr, (sizeof(sNode) * newSize));
if (!newarr)
{
perror("realloc");
exit(-1);
}
/* free old array */
free(s->arr);
s->arr = newarr;
}
int main(int argc, char **argv)
{
if (argc < 2)
{
fprintf(stderr,"Usage: app n\n");
exit(1);
}
struct String *str = string_new("");
int i;
for (i = 0; i < atoi(argv[1]); i++)
string_append(str, "anything that can go wrong, will");
}
|