0

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.

  • Why are you not using `std::string`? – Ed Heal Dec 18 '16 at 17:02
  • You need to pass the parameter by reference, not by value. See the duplicate question for more information. `s=new...` in the function has no effect on the pointer in main(), it only affects a copy of the pointer. – Sam Varshavchik Dec 18 '16 at 17:02
  • No he does not - as he is returning `s` – Ed Heal Dec 18 '16 at 17:04
  • @EdHeal yeah but i am required to use char array instead of string – Nhân Trần Dec 18 '16 at 17:18
  • Assume I have an array in the main function like this: 'a[] = {1, 2, 3, 4, 5};' When I pass this array to a function and modify its elements inside the function, it still has effect after getting out: 'void foo(int *arr)' Then why in this case I pass the pointer s to function compress_string(char *s), it doesn't change at all. That's my question. – Nhân Trần Dec 18 '16 at 17:31

0 Answers0