Hey, yeah you guessed it homework. I am trying to print a string in reverse using pointers. Only the words though. So “hello world” is “olleh dlrow”.
What I’m doing in the code below is assigning one pointer(pSentence, which is a string array of multiple words passed down from the main function) to a temporary pointer until a space, then increment backwards and print the character from the temporary pointer to the beginning of the word, then do it again. I’m currently stuck, I don’t know how to mark the beginning of the word and increment only to that. I know the while(pt != ‘0’) is not the way to do it at all. The prompt says to store the word into a temporary string(tmpStrg) and use pT to point to it, so maybe I need to do something with tmpStrg? Any help is much appreciated and thank you in advance!!
void prtWords(char *pSentence)
{
char tmpStrg[81], *pT=tmpStrg;
int length=0;
while(*pSentence != '\0')
{
while(*pSentence != ' ' && *pSentence != '/0')
{
*pT=*pSentence;
pT++;
pSentence++;
length++;
}
pSentence++;
while(length >= 0);
{
printf("%c", *pT);
pT--;
length--;
}
}
}
According to your code, I suppose here you use
tmpStrg[81]as a new string for a word, and you print the word in reverse order later.Here is your problem for overflow, you should test
\0andat the same time (and change the secondwhileto a&&with firstwhileunchanged). There is no guarantee that a sentence will end with a.When
lengthis0, you should not do anything. Change to>.You should do
pT--first, because lastpT++does not have an assignment.Here print a
when*pSentence == ' '.Work out the full code yourself as it is homework. Any further questions are welcomed.