Учёт nulTerminator и мелкие исправления

This commit is contained in:
justuser-31 2025-05-09 14:04:26 +03:00
parent 2f6bba5ce7
commit c9e69ededb

View File

@ -2,17 +2,20 @@
#include <string.h> #include <string.h>
#include <stdio.h> #include <stdio.h>
// It's base. NUL terminator.
int nulTerm = 1;
// ------------------------------------- // -------------------------------------
// BASE - String and init of this // BASE - String and init of this
// ------------------------------------- // -------------------------------------
typedef char* string; typedef char* string;
string strInit(char* s) { string strInit(char* s) {
string str = malloc(strlen(s) * sizeof(char)); string str = malloc(strlen(s) + nulTerm);
strcpy(str, s); strcpy(str, s);
return str; return str;
} }
void strResize(string* s, int new_size) { void strResize(string* s, int new_size) {
*s = realloc(*s, new_size * sizeof(char)); *s = realloc(*s, new_size + nulTerm);
} }
// -------------- END ------------------ // -------------- END ------------------
@ -22,15 +25,15 @@ void strResize(string* s, int new_size) {
// FUNCTION - basic operations // FUNCTION - basic operations
// ------------------------------------- // -------------------------------------
void strAdd(string* s, char* str_new) { void strAdd(string* s, char* str_new) {
*s = realloc(*s, strlen(*s) + strlen(str_new)*sizeof(char)); *s = realloc(*s, strlen(*s) + strlen(str_new) + nulTerm);
strcat(*s, str_new); strcat(*s, str_new);
} }
void strSet(string* s, char* str_new) { void strSet(string* s, char* str_new) {
*s = realloc(*s, strlen(str_new)*sizeof(char)); *s = realloc(*s, strlen(str_new) + nulTerm);
strcpy(*s, str_new); strcpy(*s, str_new);
} }
void strCopy(string* s1, string* s2) { void strCopy(string* src, string* dst) {
strcpy(*s2, *s1); strcpy(*src, *dst);
} }
// -------------- END ------------------ // -------------- END ------------------
@ -44,17 +47,17 @@ int numLen(double num) {
} }
char* int2Str(int* num) { char* int2Str(int* num) {
char* buffer = malloc(numLen(*num) + 2); char* buffer = malloc(numLen(*num) + nulTerm);
sprintf(buffer, "%d", *num); sprintf(buffer, "%d", *num);
return buffer; return buffer;
} }
char* float2Str(float* num) { char* float2Str(float* num) {
char* buffer = malloc(numLen(*num) + 2); char* buffer = malloc(numLen(*num) + nulTerm);
sprintf(buffer, "%f", *num); sprintf(buffer, "%f", *num);
return buffer; return buffer;
} }
char* double2Str(double* num) { char* double2Str(double* num) {
char* buffer = malloc(numLen(*num) + 2); char* buffer = malloc(numLen(*num) + nulTerm);
sprintf(buffer, "%lf", *num); sprintf(buffer, "%lf", *num);
return buffer; return buffer;
} }