#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <string.h>
int cauta(const void *x, int n, int dim_el, const void *el)
{
char *c = (char*) x;
int i;
for(i = 0; i < n; i++)
{
if(memcmp(c + i * dim_el, el, dim_el) == 0)
return 1;
}
return -1;
}
int main()
{
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
int k;
k = cauta(a, sizeof(a) / sizeof(a[0]), sizeof(a[0]), a[0]);
printf("%d", k);
return 0;
}
问题出现在注释行上。如果“x”数组中存在“el”,则该函数返回 1。这很简单,但我不明白为什么它是一个段错误。
Also, this is the call stack display when I tried debugging it line by line.
最佳答案
在您的代码中,函数参数是
int cauta(const void *x,int n,int dim_el,const void *el)
其中 el
需要一个 const void *
,而在调用时,
cauta(a,sizeof(a)/sizeof(a[0]),sizeof(a[0]),a[0]);
您传递了 a[0]
,它是一个 int
。
您需要传递一个地址,例如 &a[3]
。
也就是说,int main()
应该是 int main(void)
以符合标准。
关于c - memcmp 上的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34965377/