What I want to do is to get a string from input without having to guess at the size of the array needed beforehand, and be able to concatenate a new input string on the end of it, something like this:
Code:
char * str = instring(); //get string from input allocating just enough space for it
incat(str); //concatenate a new string to the end of str
My header file so far:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * instring(){
char * str = (char *) malloc(sizeof(char));
str[0] = '\0';
int c; //char to be put into
int i = 0; //index of string to store
while((c = getchar()) != '\n'){
str[i] = c;
str = (char *)realloc(str, (i+2) * sizeof(char));
str[i+1]='\0';
i++;
}
return str;
}
void incat(char * str1){
char * instr = instring();
int newlength = strlen(str1) + strlen(instr)
str1 = (char *)realloc(str1, (newlength + 1) * sizeof(char));
strcat(str1, instr);
}
instring seems to work all the time, but incat is not right. It seems to work for shorter strings, but strangness occurs on longer ones. Any help would be appreciated.