This is how my program works: promt user to input a string, using compress_string() function to pass the string as argument. Using a temporary queue to take all non-space characters from string, then put them back to the string. The final string will have no space at all.
#include <iostream>
#include "Queue.h"
#include <cstring>
using namespace std;
char* compress_string(char *s){
Queue q;
int cnt=0;
char tmp;
for(int i=0; i<strlen(s); i++){
if(s[i] != ' '){
q.enQueue(s[i]);
cnt++;
}
}
delete[] s;
s = new char[cnt+1];
for(int i=0; i<cnt; i++){
q.deQueue(tmp);
s[i] = tmp;
}
s[cnt] = '\0';
return s;
}
int main(){
char *s = new char[20];
cin.getline(s, 20);
s = compress_string(s);
cout << s;
return 0;
}
Here is problem: it works only when I return a pointer and then assign it to the input pointer as following:
s = compress_string(s);
If I make the compress_string() a void function which also means not return anything from it, and modify in the main function like this:
compress_string(s);
the output are now all non-sense characters.
I thought when I pass *s to the compress_string() function, it is already a pointer so it will have effect after getting out of the function. So where did everything go wrong? Thanks everyone.