Search code examples
c++pointersdynamic-memory-allocation

Removing duplicates from an array, using dynamic mem. allocation


This method is a member function of my class sets(for college), which has members,Set(pointer) and card(int)(cardinality).I am supposed to remove the duplicates and reduce the allocated memory.

The nSet pointer is being used to hold the data temporarily.

Unfortunately it is crashing, whenever called . Wat do?

void remdup() {
    int *nSet;
    for(int x=0;x<card-1;x++) {
        for(int y=x+1;y<card;y++) {
            if(Set[x]==Set[y]) {
                for(int g=y;g<card-1;g++) {
                    Set[g]=Set[g+1];
                } card--;
            }
        }
    }
    nSet=new int[card];
    for( int u=0;u<card;u++) {
        nSet[u]=Set[u];
    }
    delete Set;
    Set=new int[card];
    for(int u=0;card;u++) {
        Set[u]=nSet[u];
    }

Solution

  • You have mistake in your for loop. for(intialization;condition;increment) {}

    void remdup() {
            int *nSet;
            for(int x=0;x<card-1;x++) {
                for(int y=x+1;y<card;y++) {
                    if(Set[x]==Set[y]) {
                        for(int g=y;g<card-1;g++) {
                            Set[g]=Set[g+1];
                        } card--;
                    }
                    }
            }
            nSet=new int[card];
            for( int u=0;u<card;u++) {
                nSet[u]=Set[u];
            }
            delete Set;
            Set=new int[card];
            for(int u=0;u<card;u++) {<---
                Set[u]=nSet[u];
            }