I’ve been trying to solve this for hours. Including research, but no go. Basically, we have to create function with :
int reverseSentence(char** sentence, char ** newsentance, int maxWords){
Where it returns the number of words in a sentence.
Here’s more information:
You must maintain sentence capitalization, meaning if the sentence was capitalized, keep the
capital. If a word was capitalized, such as a name, retain the capital
- The parameter sentence is a reference to a character array with the sentence to
reverse and should not be directly modified by your function. Each word is an array
entry in sentence. - The parameter newsentance is a reference to a character array to hold the new
sentence. - The parameter maxWords is the maximum size of the character array.
- Return the number of words in the sentence
- Do not copy the strings to temporary storage and replace them in the sentence. Move
the pointers.
ex: “To be, or not to be: that is the question.” becomes ”Question the is that be: to not or be, to.
Now, the problem I have is, currently my code works. But I can’t seem to think of a way to capitalize something without getting an error. (Since we can’t make a new storage).
What I have here is basically part of my code:
char ** fptr = sentence; //front sentence
char ** lptr = sentence; //last sentence
char ** nptr = newsentance;//front of new sentance
if( isupper(**fptr)){ //if the first letter of the first word is capital set flag
capflag = 1;
}
// find last word before null sentence and also calculate size
while(**(++lptr))
++size;
--lptr;
if(capflag){
*nptr = *lptr;
**nptr = toupper(**lptr); //error here
}
Also, I had to assume that the last “word” in sentence is “” or I can’t find a way to calculate the size of the sentence. I hope someone can help me out.
I used this to test:
char ** test = malloc(1000);
*test = "To ";
*(test+1) = "be ";
*(test+2) = "or ";
*(test+3) = "not ";
*(test+4) = "to ";
*(test+5) = "be ";
*(test+6) = "";
char ** ztest = malloc(1000);
int rs = reverseSentence(test, ztest, 1000 );
Your code tries to modify a string literal, which is undefined behavior (you cannot do “ABC”[1] = 48; some implementations put string literals to readonly memory).
Try allocating space using malloc for each individual string and copy data from each string literal using memcpy.