memcmp 比较数组的段(删除重复项)
我已经为此工作了一段时间(用 C 语言)但无法弄清楚。我有一个包含字符数组的缓冲区。我已经使用 qsort 对数组进行了排序,现在一切都按正确的顺序排列了。我现在需要删除重复项(或者只打印出没有重复项的列表)。 有一个警告:字符被分为 N 个字符组(N 由用户给出)。因此,这不仅仅是将一个字符与另一个字符进行比较;而是将一个字符与另一个字符进行比较。它正在将它们之间的组进行相互比较。
例如:如果输入是 AADDBBEECCEE 并且用户给出的 N 是 2,则结果将是 AABBCCDDEE(删除了其中一个 EE)。
我知道我必须使用 memcmp,但我对语法感到困惑。我正在尝试:
i=0;
int result;
int k;
while(i<bufferSize-nValue){
result = memcmp(buffer[i], buffer[i+nValue], nValue);
if(result==0){
i=i+nValue;
}
else{
for(k=0; k<nValue; k++){
printf("%c",buffer[i]);
i++;
}
}
}
其中 buffer 是数组,nValue 是 N,bufferSize 是数组中元素的总数。 运行代码时我不断遇到分段错误。
谢谢大家的帮助!
I've been working on this for a while (in C) and can't figure it out. I have a buffer containing an array of chars. I've used qsort to sort through the array and it's all in proper order now. I now need to remove duplicates (or just print out the list without duplicates).
There's a caveat: the chars are grouped into groups of N chars (the N given by the user). So it's not just comparing one char next to the other; it's comparing groups of them against each other.
So for example: if the input is AADDBBEECCEE and the N given by the user is 2, the result would be AABBCCDDEE (with one of the EE's removed).
I know I have to use memcmp, but I'm confused about the syntax. I'm trying:
i=0;
int result;
int k;
while(i<bufferSize-nValue){
result = memcmp(buffer[i], buffer[i+nValue], nValue);
if(result==0){
i=i+nValue;
}
else{
for(k=0; k<nValue; k++){
printf("%c",buffer[i]);
i++;
}
}
}
where buffer is the array, nValue is N, bufferSize is total number of elements in array.
I keep getting segmentation fault when running the code.
Thanks for your help, everyone!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您写道:
memcmp()
接受指针。您可能指的是buffer+i
和buffer+i+nValue
作为参数。如果这就是答案,我很惊讶你的编译器没有对此发出警告。您是否激活了警告?You wrote:
memcmp()
takes pointers. You probably meanbuffer+i
andbuffer+i+nValue
for the arguments. If that's the answer, I'm surprised your compiler didn't warn about that. Did you activate warnings?