-
Notifications
You must be signed in to change notification settings - Fork 1
/
string.c
73 lines (67 loc) · 1.86 KB
/
string.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
/*****************************************************************************************
*
* IFJ - interpret of IFJ15 language
*
* dynamic string
* string with auto realocking
*
* author: Karolína Klepáčková (xklepa04)
* created: 2015-11-22
* modified: 2015-11-22
*
*****************************************************************************************/
#include <stdlib.h>
#include <string.h>
#include "string.h"
// initialization of 'string'
int initS(string_T *string)
{
string->length = 0;
string->allocatedSize = STRING_BASE_SIZE;
string->data = malloc(STRING_BASE_SIZE + 1); // +1 for '\0'
if (string->data == NULL)
{
string->allocatedSize = 0; // alocation error
return 99;
}
string->data[0] = '\0'; // string terminator
return 0;
}
// destroy 'string' and free allocated memory
void destroyS(string_T *string)
{
string->length = 0;
string->allocatedSize = 0;
free(string->data);
}
// add 'character' to end of 'string'
int addCharacterS(string_T *string, char character)
{
if (string->length >= string->allocatedSize)
{
int newSize = 2 * string->allocatedSize;
char *newData = realloc(string->data, newSize + 1);
if (newData == NULL)
return 99;
string->allocatedSize = newSize;
string->data = newData;
}
string->data[string->length] = character;
string->length++;
string->data[string->length] = '\0';
return 0;
}
// set string to length 0 (alocated memory are not free)
void cleanS(string_T *string)
{
string->length = 0;
string->data[0] = '\0'; // string terminator
}
// allocation memory for 'string' anyd copy them
char *allocString(char *string, int freeSpace)
{
int length = strlen(string);
char *newString = malloc(length + freeSpace + 1);
strcpy(newString, string);
return newString;
}