0

I'm trying to remove a string from a pointer pointer char (char **str), my function removes the string and make duplicates of the remaining strings.

void    remove_dup(char **split, char *name)
{
    char **sp;
    sp = split;
    while (*sp != NULL)
    {
        if (strncmp(*sp, name, strlen(name)) == 0)
        {
            *sp = *(sp + 1);
            sp++;
        }
        else
            sp++;
    }
}

complete code

4
  • Uh, the link says "working example"? What is your question? Commented Jul 9, 2016 at 17:46
  • example of the code, with duplicates. I want to remove duplicates. Commented Jul 9, 2016 at 17:48
  • 2
    That doesn't look like removing duplicates. Your function looks like it's meant to remove all instances of name from the list. Commented Jul 9, 2016 at 17:49
  • 1
    code.geeksforgeeks.org/fzVh9H Commented Jul 9, 2016 at 17:51

1 Answer 1

3

Skipping one string won't work. You need to keep track of read and unread strings.

This will remove duplicate entries

    void    remove_dup(char **split, char *name)
    {
        char **read,**write;
        read=write=split;
        char count=0;
        while (*read!=NULL){
            if (strncmp(*read, name, strlen(name)) == 0){
                if(count==0){
                    *(write++)=*(read++);   
                    count=1;
                }
                else{
                    //free string
                    read++;
                    continue;
                }
            }
            else
                *(write++)=*(read++);   
        }
        *write=0;
    }

If the duplicate entries are to be removed properly, strings must be freed properly. You should change the way you have initialized strings to be able to do that.

Sign up to request clarification or add additional context in comments.

1 Comment

Alternatively, because of the way the array of pointers to strings was initialized, there was no need to free the strings, but if the array was initialized with dynamically allocated strings, then there would need to be a strategy for freeing the no longer referenced memory to avoid leaks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.