[英]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您的代码有几处问题,包括
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.