Okay answer to problem as it was stated originally how to append a single character to the end of a string which DOES NOT have space allocated for it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* note that str can be NULL for a new string */
char *straddchr(char *str, int c) {
size_t len = str ? 2+strlen(str) : 2;
char *p = realloc(str, len); /* add space (need space for char and \0) */
if ( !p )
return str;
str = p;
str[len-2] = c;
str[len-1] = 0;
return str;
}
int main() {
char *str = NULL;
str = malloc(5);
strcpy(str, "Hell");
str = straddchr(str, 'o');
str = straddchr(str, ' ');
str = straddchr(str, 'w');
str = straddchr(str, 'o');
str = straddchr(str, 'r');
str = straddchr(str, 'l');
str = straddchr(str, 'd');
printf("%s\n", str);
}
And here is the second bit which inserts a character every 'n'th position
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* note that str can be NULL for a new string */
char *strinjectchr(char *str, int c, int n) {
size_t len = str ? strlen(str) + n + 1: n + 1;
str = realloc(str, len);
char *p;
int i;
if ( len == 1+n ) { /* original string was NULL */
str[n] = 0;
return memset(str, c, len-1); /* just use memset and send it all back */
}
char *copy = strdup(str);
for (i = 0, p = copy; *p != 0; p++) {
str[i++] = *p;
if ( (i > 0) && ((1+(p - copy))%n == 0) ) {
str[i] = c;
i++;
}
}
str[len] = 0;
free(copy);
return str;
}
int main() {
char *str = NULL;
str = strinjectchr(str, 'X', 25);
printf("str is: %s\n", str);
str = strinjectchr(str, '-', 5);
printf("str is: %s\n", str);
str = strdup("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
str = strinjectchr(str, '\n', 3);
printf("str is: %s\n", str);
}
strlenis not an O(1) operation. It recomputes the string length (based on finding the trailing'\0') every time you call it. It's generally better to call it once and store that in a variable, updating the variable if you add to the string, than to call it three times.strlen(string)when the null terminator has not been set tostring. This will produce segmentation fault.