I want to write a function which accepts as an argument array of characters, and the function should change the order of the words - I want the original string to be changed by the function, and not just print the sentence backwards.
Now, I wrote a program which copies the words in the opposite order to a new array of the same length, but the original array is not affected when the function is done. Here's my code:
void revSent(char* str){
int n =strlen(str);
int i=0, j=n-1;
char* rev = (char*) malloc(n+1);
while (j>0){ //Copy the words from the last one to the first one
if(str[j] ==' '){
int k = j+1;
while(str[k] != ' ' && str[k]!='\0'){
rev[i]=str[k];
k++;
i++;
}
rev[i] = ' ';
i++;
}
j--;
}
if (j==0){ //Copy the first word
int k=j;
while (str[k]!= ' ' && str[k]!= '\0'){
rev[i]=str[k];
k++;
i++;
}
rev[i]='\0';
}
char* tmp = str; //Make str point to rev and free the allocated space pointed by str
str = rev;
free(tmp);
tmp = NULL;
}
I dont want the function to return anything - I want it to stay a void function. What went wrong here and what should I change?
Thanks in advance.
Note: Im using free(tmp)
since the Im going to use as an argument for this function an array which was allocated using malloc
in the main function.
Edit: here's an example of the output I dont want:
Please, enter your sentence
I dont think it will work
I dont think it will work
And the result is
I dont think it will work
Process returned 0 (0x0) execution time : 6.141 s
Press any key to continue.
EDIT 2:
Here's example for a correct Output I want:
Please, enter your sentence
By reversed order this is what I mean
By reversed order this is what I mean
And the result is
mean I what is this order reversed By
Process returned 0 (0x0) execution time : 7.643 s
Press any key to continue.