I wanted to make a text editor program in C using ncurses, but I need a way to store the text. I cannot use a fixed array because there is no way to if the file has a few characters or hundreds of lines.
I tried using a char pointer and realloc() every time a character is added or removed, it seems to kind of work but it is a bit quirky and will randomly cause errors. I wonder if you have any ideas or know some sites where I can learn about this?
This is my progress:
Code:
char* str_new(char* data)
{
char* ptr;
ptr = (char*) malloc((sizeof(char) * (strlen(data) + 1)));
strcpy(ptr, data);
return ptr;
}
void str_cat(char* str, char* sub)
{
str = (char*) realloc(str, sizeof(str) + (sizeof(char) * (strlen(sub) + 1)));
strcat(str, sub);
}
void str_ins_char(char* str, char sub, int index)
{
str = (char*) realloc(str, (strlen(str)+2)*sizeof(char));
int i = strlen(str);
while(i >= index) {
str[i+1] = str[i];
i--;
}
str[index] = sub;
}