memcmp 上的分段错误

Segmentation fault on memcmp

#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;
}

问题出现在注释行。函数 returns 1 如果 "el" 存在于 "x" 数组中。这很简单,但我不明白为什么它是段错误。

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) 才符合标准。

您将 int a[0] 作为 const void * 传递给 cauta,这将导致错误。