C中二进制搜索中的分段错误

时间:2013-04-09 15:51:57

标签: c binary-search

我正在尝试编写一个程序来扫描包含数组中字母数的输入文件,一个排序的字母列表,要搜索的字母数,一个要搜索的字母列表。它以示例文件中显示的格式显示搜索结果。

我在运行时使用下面包含的代码获取了分段错误错误消息。现在在这篇文章得到负面反馈之前不包括适当数量的代码,我真的不知道这个分段错误的错误在哪里。我在Pastebin上包含了相关文件:

main.c

#include <stdio.h>
#include <stdlib.h>
#include "Proto.h"

int main()
{
    /* Accepts number of elements from user */
    scanf("%d", &elements);

    /* Creates dynamic array */
    array = (char *) calloc(elements, sizeof(char));

    /* Copies sorted values to the dynamic array */
    for(i = 0; i < elements; i++)
    {
        scanf("%s", &array[i]);
    }

    /* Accepts number of elements to search */
    scanf("%d", &search);

    /* Searches for elements in sorted array one at a time */
    for(i = 1; i <= search; i++)
    {
        /* Accepts value to search */
        scanf("%s", &value);

        /* Resets counter to 0 */
        count = 0;

        /* Finds location of element in the sorted list using binary search */
        location = binarySearch(array, value, 0, (elements-1));

        /* Checks if element is present in the sorted list */
        if (location == -1)
        {
            printf("%4s not found!\n", value);
        }

        else
        {
            printf("%4s found at %4d iteration during iteration %4d\n", value, location, count);
        }
    }
    free(array);
}

BinarySearch.c

#include <stdio.h>
#include "Proto.h"

int binarySearch(char * nums, char svalue, int start, int end)
{
    middle = (start + end) / 2;

    /* Target found */
    if (nums[middle] == svalue)
    {
        return middle;
    }

    /* Target not in list */
    else if( start == end )
    {
        return -1;
    }

    /* Search to the left */
    else if( nums[middle] > svalue )
    {
        count++;
        return binarySearch( nums, svalue, start, (middle-1) );
    }

    /* Search to the right */
    else if( nums[middle] < svalue )
    {
        count++;
        return binarySearch( nums, svalue, (middle+1), end );
    }
}

Proto.h

#ifndef _PROTO_H
#define _PROTO_H

char * array;
int elements, search, location, count, middle, i;
char value;
int binarySearch(char *, char, int, int);

#endif

Sample Input/Output

Sample Input file:
6
a d n o x y
3
n x z

Sample Output file:
  n found at    2 during iteration    0. 
  x found at    4 during iteration    1.
  z not found!

1 个答案:

答案 0 :(得分:1)

我没有检查整个代码,但是我在main.c

中看到了这个错误

你的代码

    /* Creates dynamic array */
    array = (char *) calloc(elements, sizeof(char));

    /* Copies sorted values to the dynamic array */
    for(i = 0; i < elements; i++)
    {
            scanf("%s", &array[i]);
    }

错了。你的array应该是双指针char **array

    /* Creates dynamic array */
    array = calloc(elements, sizeof(char*));

    /* Copies sorted values to the dynamic array */
    for(i = 0; i < elements; i++)
    {
            scanf("%ms", &array[i]);
    }

尝试划分代码,找出导致问题的部分,并通过一小部分代码返回增益,这将有助于找出解决方案