2016-01-23 221 views
-3
#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。這是一個簡單的,但我不明白究竟爲什麼它是一個segmfault。分段故障

Also, this is the call stack display when I tried debugging it line by line.

+6

太不完整,能夠提供幫助。 –

+0

@iharob,對不起,我編輯完整的代碼 –

+0

請檢查指針數學;-) –

回答

3

在你的代碼中,函數的參數是

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)以符合標準。

0

你傳遞一個inta[0]cauta作爲const void *那將導致錯誤。