I’m trying to append a char to string.
I tried
char *string = malloc(strlen(text) * sizeof (char));
for(i=0, i <n; i++)
{
j = i;
while (j <= strlen(text))
{
string[strlen(string)] = text[i];
j = j + n;
}
string[strlen(string)] = '\0';
printf("%s", string);
string = "";
}
My goal is creating variations of text.I got segmentation fault with this code. What am i doing wrong?
EDIT: to be more clear what i want to do is:
lets say text = “asdfghjk”
And for n = 3 i want the following output:
afj
sgk
dh
This is what you want.
First of all, a string with terminating zero will take strlen()+1 bytes of space. Not just strlen().
Second, don’t ever use strlen() in a loop. Precalculate it in int and use it.
Third, you had an error: you had text[i], but meant text[j].
Fourth, as authors of previous answers mentioned, you can not calculate a length of a string if it does not have terminating zero yet.
Fifth, you don’t need to clear a string after each iteration since overwriting its characters and adding new terminating zero will make it completely new string.