简体   繁体   中英

How to delete a specific string from an array of strings in C?

I need a function that receives an array of pointers to strings and it's size. Then it should seek for those strings which occur in the array more than once - then I have to delete them and realloc the array. Function should return new size of the array. I'm trying to solve this, and not sure what`s wrong.

I want to move each string, that I want to delete, to the end of the array and then delete it, but not sure when the "realloc" should happen.

#include<stdio.h>
#include<stdlib.h>

int DeleteString(char** tab, int n){
    char* check=malloc(sizeof(char)*100);
    int deleted;
    int i,j,g,h;

    for(i=0;i<n;i++){
        strcpy(check, tab[i]);
        for(j=0;j<n;j++){
            if(strcmp(check, tab[j]) == 0){     
                deleted++;
                char* temp = malloc(sizeof(char)*100);
                for(h=j;h<n-1;h++){
                    strcpy(temp, tab[h+1]);
                    strcpy(tab[h+1], check);
                    strcpy(tab[h], temp);       
                }
            }

            if(deleted>0){
                realloc(tab, sizeof(char*)*(n-deleted));
            }
        }
    }
    return n-deleted;
}

For now there is "Segmentation fault" error

The reason for the SEGMENTATION FAULT is tab[0] store the address of the variable which stores the actual string. Here tab[i] is in for loop,hence when it tries to fetch tab[1] itself memory error.

for(i=0;i<n;i++){
    strcpy(check, tab[i]);...}

FOR EXAMPLE:

 char *foo = "something";
 char **ptr2;
 ptr2 = &foo;
 printf("check = %s", *ptr2); 
 for(int i=0;i<9;i++){  
   printf(" check = %c",  ptr2[i]);
 }

Output

check = something check = 4check = �check = pcheck =

Actally it is an error.

Oops, your code contains numerous problems, because you failed to observe some major rules of C language:

  • every non static variable shall be initialized (what about deleted ?)
  • any object that was malloced shall be freed (what about check and temp .)
  • never change something that was passed as an input parameter to a function, or do not expect the change to be visible on return ( tab has to be considered here because of next line).
  • allways assign the result of realloc because it can be different from the input pointer ( realloc(tab, sizeof(char*)*(n-deleted)); ).

The first one is probably the cause of the segmentation fault because as deleted is unitialized its value is just undeterminated. But all problems should be fixed.

First of all, don't forget to initialise variables like deleted , as it has been said in other answers.

Next, you are supposed to free memory (as you are deleting items) and you only call malloc(3) ). That seems a little counter-common sense, doesn't it?

Third, you make a lot of string copying in the loops, while it should be more efficient just to move pointers up, so you don't need to realloc the string elements and copy the cell contents (by the way, are you sure those strings will be feed to the function as malloc() d strings? I will assume that as you do)

Fourth, consider sorting the array first, so all the similar strings will be adjacent in the array. This has a cost O(n*log(n)) that, appended to the delete next string if equal (with cost O(n) ) makes total cost O(n*(log(n)+1)) or O(n*log(n)) and not O(n^2) which is your actual cost)

Once sorted, only the strings deleted should be free(3) d, the pointers moved back to the start of the array as holes get appearing, and finally(when all is finished) you can just realloc(3) the array of pointers (only once, not at every pass through the loop)

Remaking the example is out of the scope of this answer, as it looks actually some school exercise. Sorry for that. I'm sure that the other hints will help you to retry the exercise with more success.

And think: thinking before writing is how one succeeds in this job.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM