I’m learning C and I need to deal with some c strings. I’m really shaky with C, especially on the freeing memory stuff, so please inform me if my question is wrong.
I have an empty c string, say size 5, and I want to append a character to it one character at a time. So up to the first 9 characters everything is fine, but once you have more than nine, you need to extend the size of the array to store your character. So I thought the easiest way of doing this was to use strcat like:
char orig[] = "hello";
char temp[1];
temp[0] = ' ';
strcat(orig, temp);
temp[0] = 'w';
strcat(orig, temp);
// etc
The string prints out what I expect when I do printf(orig), but I’m worried because I didn’t extend the size of orig, since printf("%d", sizeof(orig)) is still 5, but should be bigger due to adding the temps. What’s the best(simplest) way of solving this problem?
Since
origis allocated statically, you cannot free and re-allocate it. But you can pre-allocate more space to fit additional characters, like this:Note that
sizeof(orig)would start at 100, and remain at 100, no matter what’s the length of the string inside it. To find out the current length of the C string inside it, usestrlen(orig).