-
Notifications
You must be signed in to change notification settings - Fork 0
/
string.c
61 lines (53 loc) · 1.37 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
/**
* Project: Compiler for IFJ21 language
*
* Brief: Dynamic string to store text
*
* Author: Stepan Bakaj <xbakaj00@stud.fit.vutbr.cz>
*
* Date: 23-10-2021
*/
#include "string.h"
#include <stdbool.h>
#include <stdlib.h>
#define ALLOCATE_LENGTH 8
string_ptr_t string_init(){
string_ptr_t string = (string_ptr_t) malloc(sizeof(struct string));
if (!string){
return NULL;
}
string->string = NULL;
string->alloc_lenght = 0;
string->lenght = 0;
return string;
}
void string_free(string_ptr_t string){
free(string->string);
string->string = NULL;
free(string);
string = NULL;
}
bool string_append_character(string_ptr_t string, char a){
if (string->lenght + 1 >= string->alloc_lenght){
string->alloc_lenght = string->lenght == 0 ? ALLOCATE_LENGTH : string->alloc_lenght * 2; //twice much memmory
string->string = (char *) realloc(string->string,string->alloc_lenght);
if (!string->string){ // failed realloc
return false;
}
}
string->string[string->lenght++] = a;
string->string[string->lenght] = '\0';
return true;
}
char* get_char_arr(string_ptr_t string)
{
return string->string;
}
int string_to_int (string_ptr_t string)
{
return atoi(string->string);
}
double string_to_dec (string_ptr_t string)
{
return atof(string->string);
}