-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgetwords.h
56 lines (41 loc) · 1.06 KB
/
getwords.h
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
#ifndef GETWORDSH
#define GETWORDSH 1
#include "getword.h"
char** getwords(char* line, int* numwords) { // TODO: Take a size param to make this safe
char* word;
int cap = 2; // Start with 2 word limit
char** result = malloc(cap * sizeof(char*));
*numwords = 0;
while((word = getword(' ', &line))) {
#if DEBUG
printf("Inside getwords - Got word: [%s], rest of line: [%s]\n", word, line);
#endif
if(*numwords >= cap / 2) {
cap = (cap + 2) * 2; // TODO: Why does this need to be cap + 2 ?
result = realloc(result, cap * sizeof(char*));
#ifdef DEBUG
printf("Inside getwords - Reallocated.\n");
#endif
}
#ifdef DEBUG
printf("Inside getwords - Numwords: %d, Cap: %d\n", *numwords, cap);
#endif
result[*numwords] = word;
#ifdef DEBUG
printf("Inside getwords - Assigned word to list.\n");
#endif
(*numwords)++;
}
if(0 == *numwords) {
#ifdef DEBUG
printf("Inside getwords - No words\n");
#endif
free(result);
return NULL;
}
#ifdef DEBUG
printf("Inside getwords - Finished getting words: %d\n", *numwords);
#endif
return result;
}
#endif