菜鸟,问个问题

martenyong 2009-08-30 01:44:44
写的一个有关anangrams的程序,
用于检验两个单词是不是含有相同字母的(可以顺序不同)。
总体的思路是,如果两个单词的长度一样,那么就把其中的字幕按照子目标的顺序排列,
如果两个单词排列得到的结果相同,即返回“正确”,否则,则是“错误”
程序如下:

include<iostream>
using namespace std;

int compare(char list1[20],char list2[20],int count) //检验函数
{

int i=0,j=0,n=0;

for(i=count;i>=1;i--) //第一个单词冒泡排序
{
int currentMaxIndex1=0;
char currentMax1=list1[0];

for(j=1;j<=i;j++)
{
if(currentMax1<list1[j])
{
currentMax1=list1[j];
currentMaxIndex1=j;
}
}

if(currentMaxIndex1!=i)
{
list1[currentMaxIndex1]=list1[i];
list1[i]=currentMax1;
}
}


for(i=count;i>=1;i--) //第二个单词,冒泡排序
{
int currentMaxIndex2=0;
char currentMax2=list2[0];

for(j=1;j<=i;j++)
{
if(currentMax2<list2[j])
{
currentMax2=list2[j];
currentMaxIndex2=j;
}
}

if(currentMaxIndex2!=i)
{
list2[currentMaxIndex2]=list2[i];
list2[i]=currentMax2;
}
}

for(i=0;i<count;i++)
{
if(list1[i]==list2[i])
n++;
else
{
return 0;
break;
}
}

if(n==count)
return 1;
else
return 0;

}

int main()
{
char list1[20]={0},list2[20]={0};
int i,count1=0,count2=0,result;

cout<<"please input the first word:"<<endl;
cin.getline(list1,20);
cout<<"the first word is:"<<endl;
for (i=0;i<sizeof(list1);i++)
{
cout<<list1[i];
count1++;
}
cout<<endl;


cout<<"please input the second word:"<<endl;
cin.getline(list2,20);
cout<<"the second word is:"<<endl;
for (i=0;i<sizeof(list2);i++)
{
cout<<list2[i];
count2++;
}
cout<<endl;

if (count1==count2)
{
result=compare(list1,list2,count1);
if(result==1)
cout<<"the two words are anagrams ^^"<<endl;
else
cout<<"the two words are not anagrams!"<<endl;
}
else
cout<<"the two words are not anagrams!";

return 0;
}


这个程序编译的时候没有问题,运行的时候,也能达到目的,但是运行时会出这样的问题:

Run-Time Check Failure #2 - Stack around the variable 'list2' was corrupted.

请问这是怎么回事呀,
谢谢各位大侠了~。
...全文
53 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
stjay 2009-08-30
  • 打赏
  • 举报
回复
数组存放字符串时应多留一个位置
即其长度=字符串长度+1(字符串结束符\0)

改成试试:
char list1[21]={0},list2[21]={0};

16,548

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC相关问题讨论
社区管理员
  • 基础类社区
  • AIGC Browser
  • encoderlee
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

        VC/MFC社区版块或许是CSDN最“古老”的版块了,记忆之中,与CSDN的年龄几乎差不多。随着时间的推移,MFC技术渐渐的偏离了开发主流,若干年之后的今天,当我们面对着微软的这个经典之笔,内心充满着敬意,那些曾经的记忆,可以说代表着二十年前曾经的辉煌……
        向经典致敬,或许是老一代程序员内心里面难以释怀的感受。互联网大行其道的今天,我们期待着MFC技术能够恢复其曾经的辉煌,或许这个期待会永远成为一种“梦想”,或许一切皆有可能……
        我们希望这个版块可以很好的适配Web时代,期待更好的互联网技术能够使得MFC技术框架得以重现活力,……

试试用AI创作助手写篇文章吧