在继续使用其他功能之前,程序停止的原因是什么?

时间:2017-04-13 01:50:43

标签: c++ string binary-search

我正在进行二进制搜索,以便在此程序排序后使用,我不确定如何在按字母顺序对字母进行排序后停止崩溃。

Main.cpp的

#include <iostream>

#include "ReadString.h"
#include "SortString.h"
#include "SearchString.h"

using namespace std;

int main()
{
    int i;
    int column = 500;
    int row = 20;
    char    *inputsearch;

    cout << "How many names will you enter? ";
    cin >> row;

    while (row > 20 || row < 0)
    {
        cout << "Error: Please do not enter more than 20 or less than 0: ";
        cin >> row;
    }

    char **p = ReadString(row, column);

    cout << "Printed: " << endl;

    for (i = 0; i < row; i++)
    {
        cout << *(p + i) << endl;
    }

    StringSort(p, row);
    cin >> inputsearch;
    cout << inputsearch;
    SearchString(p, inputsearch);




    for (i = 0; i < row; i++)
        delete[] p[i];

    delete[] p;

    return 0;
}

Readstring.cpp

#include <iostream>
#include <cstring>

#include "ReadString.h"

using namespace std;

char **ReadString(int row, int column)
{
    char **String = 0;
    int i;
    String = new char *[row];
    int NumChars;

    for (i = 0; i < row; i++)
        String[i] = new char[column];

    for (i = 0; i < row; i++)
    {
        cout << "Enter name " << i + 1 << ": ";
        cin >> String[i];

        NumChars = strlen(String[i]);
    }

    return String;
}

Readstring.h

    #ifndef READ_STRING_H
#define READ_STRING_H

char **ReadString(int, int);


#endif

SortString.cpp

#include<iostream>
#include<conio.h>
#include<stdio.h>

#include "SortString.h"

using namespace std;

void StringSort(char **str, int row)
{
    char t[20];
    int i, j, k;

    for (i = 1; i < row; i++)
    {
        for (j = 1; j < row; j++)
        {
            //compare each 
            if (strcmp(str[j - 1], str[j])>0)

            {
                strcpy(t, str[j - 1]);
                strcpy(str[j - 1], str[j]);
                strcpy(str[j], t);
            }
        }
    }
    cout << "Strings (Names) in alphabetical order : \n";
    for (i = 0; i < 5; i++)
    {
        cout << str[i] << "\n";
    }
    getch();
}

SortString.h

#ifndef SORT_STRING_H
#define SORT_STRING_H

void StringSort(char **, int);

#endif

SearchString.cpp

#include <string.h>

#include "SearchString.h"

int SearchString(char **p, char *inputsearch)
{
    int     First;
    int     Middle;
    int     Last;

    First = 0;
    Last = strlen(*p) - 1;
    do {
        Middle = (First + Last) / 2;
        if (inputsearch == p[Middle])
            return Middle;
        else
            if (inputsearch > p[Middle])
                First = Middle + 1;
            else
                Last = Middle - 1;
    } while (First <= Last);
    return -1;
}

SearchString.h

#ifndef Search_String_H
#define Search_String_H

int SearchString(char **, char *);

#endif

1 个答案:

答案 0 :(得分:0)

当你这样做的时候     cin&gt;&gt;串[I]; 在ReadString.cpp中,您不确保输入长度加上null终止符的字符数小于'column'允许的数组。如果您键入的字符数多于列的宽度,则会损坏您的freestore堆。