i wanted to know if you think my implementation is good for making strings.
#String library in C
3 messages · Page 1 of 1 (latest)
In throwErr, you should print to stderr instead of stdout. You can do that using fprintf.
In stringInit you malloc data twice then free one of the copies at the end, why? Also, you can just use strcpy, it null terminates the string for you.
I notice that you realloc in almost every function. You could just keep track of the size (i.e differentiate between used size and unused size), then realloc when you need to. That's much more efficient than resizing every time you change the length of the string.
Since you have getters and setters, I assume you want string to be an opaque type. Currently, someone using this library can simply access string->data without using the stringGet function for example. You can make string a pointer to an incomplete type instead like so:
str.h:
typedef struct StringStruct *string; /* This is an incomplete type, so we can't access it's members */
str.c:
typedef struct StringStruct { /* Complete the type for str.c */
size_t size;
char *data;
} StringStruct;
In stringAt you take in index as an int, then you make sure it's > 0. Why not just use an unsigned type e.g size_t, then you don't have to check.
Your strCmp function returns an int, either 1 or 0, depending on if the strings are equal. Two things here, 1. That's not what strcmp is normally expected to do (maybe change this to strEqual?). 2. If you only plan on returning two values, just use bool.
I haven't actually run the code, but other than the things I mentioned, it looks fine.