下面的代码运行于VS2012的编译环境,目的是为了对出现的19个国家名称进行按大到小排序,遗憾的是,结果结果并没有得出。
但有一点,若是将主程序中的 pCountryName这一指针数组中的"United States of America"缩减一个字符如变为"United State of America",程序将运行无恙。
同样的代码,放置于Vc++6.0的编译环境却不会出现问题!
程序在执行过程中,执行至内部函数HeapAlloc()时会出问题。
大神,求破!
// CountryOrder.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "string.h"
#include "iostream" strong text
#include "malloc.h"
#define COUNTRYNAME 100
using namespace std;
void NameSort(char** pName)
{
int nlen=19;
bool* pbflg=new bool[nlen];//存储临时标识状态
for(int i=0; i<nlen; i++)//动态数组的初始化
{
pbflg[i]=false;
}
int ncmpNum=0, nMinPos=0;
char *pstrMin=new char(COUNTRYNAME);
char *pstrMax=new char(COUNTRYNAME);
strcpy(pstrMin, pName[0]);
for (int i=1; i<nlen;i++)//获取最小的字符串,及其位置
{
ncmpNum=strcmp(pstrMin, pName[i]);
if (ncmpNum>0)
{
nMinPos=i;
strcpy(pstrMin, pName[i]);
}
}
for(int i=0; i<nlen; i++)//将各个字符串分别与最小字符串进行比较,每次只获取当前序列中最大的字符串
{
if (i==nMinPos)
{
continue;
}
int nRecord=0;
int k=0;//用于判断选择要处理的数据位置
while (pbflg[k])
{
k++;
}
nRecord=k;
strcpy(pstrMax, pstrMin);//以最小值为基准参考
for(int j=k; j<nlen; j++)//获取当前序列中的最大值
{
if(pbflg[j]||j==nMinPos)//跳过已经输出的字符串以及对参考位的比较
{
continue;
}
ncmpNum=strcmp(pstrMax,pName[j]);
if (ncmpNum<0)
{
pbflg[nRecord]=false;
pbflg[j]=true;
nRecord=j;
strcpy(pstrMax, pName[j]);
}
}
cout<<pstrMax<<endl;
}
cout<<pstrMin<<endl;
// delete pstrMin;
// delete pstrMax;
// delete []pbflg;
// pstrMax=NULL;
// pstrMin=NULL;
// pbflg=NULL;
}
int _tmain(int argc, _TCHAR* argv[])
{
char* pCountryName[19]={"China", "United States of America", "United Kingdom", "Uruguay", "Uzbekistan","Vanuatu","Vatican City","Venezuela","Japan", "Hong Kong", "Macau", "Chinese Tapei","Vietnam","Wallis and Futuna ","Western Sahara","Yemen","Yugoslavia","Zambia","Zimbabwe"};
NameSort(pCountryName);
return 0;
}
不知道你这个问题是否已经解决, 如果还没有解决的话: