Добавление безразмерной строки с динамическим выделением памяти

This commit is contained in:
justuser-31 2025-05-04 17:16:00 +03:00
parent fbe0514d1b
commit 08e39eca09
2 changed files with 35 additions and 0 deletions

15
examples/string.c Normal file
View File

@ -0,0 +1,15 @@
#include <stdio.h>
#include "../libs/string.h"
int main() {
string test = strInit("Hello?");
printf("String now: %s\n", test);
strAdd(&test, " World?");
printf("String now: %s\n", test);
strSet(&test, "Another intresting test with string");
printf("String now: %s\n", test);
free(test);
return 0;
}

20
libs/string.h Normal file
View File

@ -0,0 +1,20 @@
#include <stdlib.h>
#include <string.h>
typedef char* string;
string strInit(char* s) {
string str = malloc(strlen(s) * sizeof(char));
strcpy(str, s);
return str;
}
void strAdd(string* s, char* str_new) {
*s = realloc(*s, strlen(*s) + strlen(str_new)*sizeof(char));
strcat(*s, str_new);
}
void strSet(string* s, char* str_new) {
*s = realloc(*s, strlen(str_new)*sizeof(char));
strcpy(*s, str_new);
}
void strCopy(string* s1, string* s2) {
strcpy(*s2, *s1);
}