我最近加入了 Stackoverflow 社区,因为我不得不问这个问题。我一直在网站上寻找可能的解释和解决方案,但到目前为止,没有任何东西能启发我。我的错误可能是由一行非常具体的代码引起的。我正在尝试创建一个读取结构投票数组的函数,(结构包含整数成员编号、char *类别、char *nominee)并将包含相同数字和类别的所有投票复制到另一个结构数组。基本上是为了显示所有重复的投票。
typedef struct
{
int member;
char *categ;
char *nom;
}Vote
Vote vote(int member, char *categ, char *nom)
{
Vote result;
result.member = member;
result.categ = categ;
result.nom = nom;
return result;
}
int votes_count(Vote *v, int n, Vote *v1)
{
int result = 0;
int *index = malloc(sizeof(int) * 1000);
int a = 0;
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
if (a == 0 && v[i].member == v[j].member && strcmp(v[i].categ, v[j].categ) == 0)
{
v1[result++] = vote(v[j].member, str_dup(v[j].categ), str_dup(v[j].nom));
index[a++] = j;
}
for (int b = 0; b < a; ++b)
{
if( a > 0 && v[i].member == v[j].member && strcmp(v[i].categ, v[j].categ) == 0 && j != index[b])
{
v1[result++] = voto(v[j].member, str_dup(v[j].categ), str_dup(v[j].nom));
index[a++] = j;
}
}
}
}
return result;
}
之后,它返回包含所有重复项的新数组的元素数。我想使用一个整数数组来保存所有行索引,这样函数就不会读取和复制它已经计算过的行。 抱歉,如果代码难以理解,如果需要,我可以进行编辑以使其更易于理解。感谢您的回答。 P.S:我是葡萄牙语,语法错误提前道歉
最佳答案
- 如果您的唯一目的是获取重复项,则只需与元素之前出现的元素进行比较
- 你不需要
index[]
数组
为简单起见,我使用了两个整数数组,您应该将它们更改为您的结构数组,并更改比较函数。
unsigned fetchdups(int orig[], int dups[], unsigned count)
{
unsigned this, that, ndup=0;
for (this=1; this<count; this++){
for (that=0; that<this; that++){
/* change this to your compare() */
if(orig[that] == orig[this]) break;
}
if (this == that) continue; /* no duplicate */
dups[ndup++] = this;
}
return ndup;
}
关于c - 返回整数时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49478685/