简体   繁体   English

在 C 程序中使用带有指针数组的 strcmp() function

[英]Using strcmp() function with pointer array in C program

I'm trying to detect duplicate strings in a pointer array.我正在尝试检测指针数组中的重复字符串。 I want to detect if there is any duplication with strcmp() function and want to remove duplications except the first one however the command line is giving error when I add strcmp() function: Segmentation fault (core dumped)我想用 strcmp() function 检测是否有任何重复,并想删除除第一个重复之外的重复,但是当我添加strcmp() function: Segmentation fault (core dumped)时命令行给出错误

Here is my code;这是我的代码; and size is equal to size of the products array.并且大小等于产品数组的大小。

FILE* temp_file_to_read = fopen("temp.txt", "r");
char temp_line[256];  
char *products[256];
int j = 0;
        while(fgets(temp_line, sizeof(temp_line), temp_file_to_read)){
                //printf("%s", temp_line);
                products[j] = strdup(temp_line);
                printf("%s", products[j]);
                j++;
        }


         for(int i = 0; i< size; i++){
                    for(int j = i+1; j <  size; j++){
                            if(strcmp(products[i], products[j])==0){
                                    printf("%s is exist\n", products[j]);
                            }
                    }
            }

I'm guessing that your file doesn't have 256 products that are exactly 256 characters in length each, so your products array isn't full.我猜你的文件没有 256 个产品,每个产品的长度正好是 256 个字符,所以你的products数组不完整。 So when you do strcmp(products[i], products[j]) , you will at some point be trying to use garbage pointers as if they point to a genuine string, and that's where you're getting a segfault.因此,当您执行strcmp(products[i], products[j])时,您有时会尝试使用垃圾指针,就好像它们指向真正的字符串一样,这就是您遇到段错误的地方。

There are several things wrong with your code, including您的代码有几处问题,包括

  • you probably want to be breaking up your file at new lines, not just every 256 characters (though I could be wrong)您可能希望在新行中拆分文件,而不仅仅是每 256 个字符(尽管我可能是错的)
  • you should check to make sure you don't try to create more than 256 products, otherwise you'll overflow your array你应该检查以确保你不要尝试创建超过 256 个产品,否则你会溢出你的数组
  • when doing the string comparisons, only go as far as the number of products you have, rather than blindly to the end of the array在进行字符串比较时,仅 go 就您拥有的产品数量而言,而不是盲目到数组的末尾

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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