-2
我正在使用二進制搜索以便在此程序排序後使用,但我不確定如何在按字母順序排序字母后停止崩潰。在繼續使用其他功能之前,程序停止了什麼?
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
而當您使用調試器遍歷代碼時,一次一行,檢查所有變量的值,直到調試器檢測到崩潰的那一刻,您做了什麼觀察? –
您的緩衝區大小不一致。有時候是500.有時候是20。我懷疑某處存在緩衝區溢出。但是既然你使用C++,你應該使用'std :: string'和'std :: vector'。 –