This is my function that is supposed to flip a string such as “Today is a beautiful day”
into “day beautiful a is Today” My nextword function (inside flipstring function) return the index of the beginning of every word in the string and also places ‘\0’ after the word. When I use the function is get the error, segmentation fault (core dumped) and I can’t figure out why.
void flip(char *str)
{
// reverse the order of the words
char buf[256];
int i[2],k,j=0,c=0;
//set k to the index of the first word in str
k = nextword(str);
//Create an array (i) of the index of the beginning of every word
//nextword also places a '\0' after every word in str
while ( k != -1)
{
i[j] = k;
j++;
k = nextword(NULL);
}
//place each word in buf in reverse order
//replace the eos with a space
for ( j=j-1 ; j >= 0 ; j--) //starts with index of last word in string str
{
buf[c]=str[i[j]];
while(buf[c]!='\0')
{
c++;
buf[c]=str[i[j]+c];
}
buf[c] = ' '; //replaces '\0' after every word with a space
c=c+1;
}
buf[c] = '\0'; //Places eos at the end of the string in buf
printf("%s\n",buf[0]);
}
Call it,
void main(void)
{
char str[] = "Today is a beautiful day!\t\n";
flip(str);
//printf("%s",str);
}
In
printf("%s\n",buf[0]);you’re passing a character to printf instead of a string which will cause a segmentation fault. Useprintf("%s\n", buf);instead.Also you aren’t copying the words correctly, in
buf[c]=str[i[j]+c];c is not the offset from the beginning of the current word but from the beginning of buf, you should use another counter to use as the offset.