分段错误发生在函数un()中,它返回两个数组的并集 但这里是完整的代码以防万一。 我已经尝试在un()中添加一些print语句但它仍然显示Segmentation fault而没有别的。
我正在使用GCC。
#include <stdio.h>
#include <stdlib.h>
void input_set(int* set, int size) {
int i;
for(i = 0; i < size; i++) {
scanf("%d", set+i);
if(i != 0 && set[i] == set[i-1]) {
printf("A set cannot have repeated values. Enter again!\n");
i--;
}
}
}
void display_set(int *set, int size) {
int i;
printf("{ ");
for(i = 0; i < size-1; i++)
printf("%d, ", set[i]);
printf("%d }\n\n", set[size-1]);
}
int* difference(int *setA, int sizeA, int *setB, int sizeB, int *size) {
int *setC = malloc(sizeof(int) * (sizeA < sizeB) ? sizeA : sizeB);
int i, j, present = 0;
*size = 0;
for(i = 0; i < sizeA; i++) {
for(j = 0; j < sizeB; j++)
if(setA[i] == setB[j]) {
present = 1;
break;
}
if(!present)
setC[(*size)++] = setA[i];
present = 0;
}
return setC;
}
int* intersection(int *setA, int sizeA, int *setB, int sizeB, int *size) {
int size1;
int *set1 = difference(setA, sizeA, setB, sizeB, &size1);
int *set2 = difference(setA, sizeA, set1, size1, size);
return set2;
}
int* un(int *setA, int sizeA, int *setB, int sizeB, int *size) {
int size1, size2, size3;
int i;
int *s1 = difference(setA, sizeA, setB, sizeB, &size1);
int *s2 = intersection(setA, sizeA, setB, sizeB, &size2);
int *s3 = difference(setB, sizeB, setA, sizeA, &size3);
int *set = malloc(sizeof(int) * (size1 + size2 + size3));
*size = 0;
for(i = 0; i < size1; i++)
set[*(size)++] = s1[i];
for(i = 0; i < size2; i++)
set[*(size)++] = s2[i];
for(i = 0; i < size3; i++)
set[*(size)++] = s3[i];
return set;
}
void main() {
int *setA, *setB, *setC;
int sizeA, sizeB, size;
printf("Enter the size of set A and B : ");
scanf("%d %d", &sizeA, &sizeB);
setA = malloc(sizeof(int)*sizeA);
setB = malloc(sizeof(int)*sizeB);
printf("Enter the values in set A :\n");
input_set(setA, sizeA);
printf("Enter the values in set B :\n");
input_set(setB, sizeB);
printf("A union B = ");
setC = un(setA, sizeA, setB, sizeB, &size);
display_set(setC, size);
printf("A intersection B = ");
setC = intersection(setA, sizeA, setB, sizeB, &size);
display_set(setC, size);
printf("A - B = ");
setC = difference(setA, sizeA, setB, sizeB, &size);
display_set(setC, size);
printf("B - A = ");
setC = difference(setB, sizeB, setA, sizeA, &size);
display_set(setC, size);
}
我们非常感谢您对代码质量的任何帮助甚至评论。
答案 0 :(得分:6)
toto.c:25:54: warning: operator '?:' has lower precedence than '*'; '*' will be evaluated first [-Wparentheses]
int *setC = malloc(sizeof(int) * (sizeA < sizeB) ? sizeA : sizeB);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ^
我认为使用更好的编译器进行编译并激活警告会给你一些好的指示......