Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Array problem (http://www.go4expert.com/forums/array-problem-t2673/)

chadr6 23Jan2007 23:40

Array problem
What I need to do is implement a function with the prototype:

void squeeze(int arr[], int& size, int val);

The function has to remove all occurrences of val from arr and update size accordingly. I am quite new to C++ and am not able to figure out how to do this. Does anyone have any ideas?


chadr6 23Jan2007 23:42

Re: Array problem
I forgot to mention that this has to be done in C++

DaWei 24Jan2007 00:13

Re: Array problem
You can't resize an ordinary array unless it has been created on the heap. If you reallocate it, you have to be prepared to update the pointer to its (possibly new) location, and remember to free it. You can, of course, remove unwanted values and modify the size variable. That won't actually resize the array, and you can't lengthen it.

To do that, you would begin at the beginning, find the first value to be tossed, copy all elements from the next to the end of the array from that location onward, begin from there, wash, rinse, and repeat until done. It would require a little more code to zero-out from the new end to the old end.

Since you're using C++, I would recommend a vector (from the STL). This is a class with array features, much like a string-class string.

If you want to do it either way, toss some code here and ask about any problems you may have.

All times are GMT +5.5. The time now is 03:41.