1

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

我在运行时收到一条分段错误错误消息,其中包含我在下面包含的代码。现在,在这篇文章因未包含正确数量的代码而受到负面反馈之前,我真的不知道这个分段错误的错误在哪里。我在 Pastebin 上包含了相关文件:

主程序

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

二进制搜索.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 );
    }
}

原型.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 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!
4

1 回答 1

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]);
    }

尝试划分您的代码并找出导致问题的部分并用一小部分代码获得收益,这将有助于找出解决方案

于 2013-04-09T15:59:54.677 回答