I'm trying to reverse the letters for words in a sentence. I am also trying to store these words in a new char array. At the moment I getting a runtime error, which for all my tweaking I can not solve. My approach is to create a new char array the same length as the sentence. Then loop through the sentence until I reach a ' ' character. Then loop backwards and add these characters to a word. Then add the word to the new Sentence. Any help would be much appreciated.
int main(void) {
char sentence [] = "this is a sentence";
char *newSentence = malloc(strlen(sentence)+1);
int i,j,start;
start = 0;
for(i = 0; i <= strlen(sentence); i++)
{
if(sentence[i] == ' ')
{
char *word = malloc((i - start)+1);
for(j = sentence[i]; j >= start; j--)
{
word[j] = sentence[j];
}
strcat(newSentence,word);
start =sentence[i +1];
}
}
printf("%s",newSentence);
return 0;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…