注册 登录
编程论坛 C++教室

读取位置时发生访问冲突

yhyoin 发布于 2013-10-24 09:11, 3972 次点击
编写一个函数,判断输入的一串字符是否为“回文”。

#include "stdafx.h"
#include<string>
#include<iostream>
using namespace std;

bool judge(char *p)
{
    int start=0;
    int end=0;
    int i=0;
    start=i;
    while(p[i]!='/0')
        i++;
    end=i-1;
    while(start<end)
    {
        if(p[start]!=p[end])
            return false;
        start++;
        end--;   
    }
    return true;
}


int _tmain(int argc, _TCHAR* argv[])
{
    char *p=new char[20];
    cin.getline(p,20);


    if(judge(p)==true)
        cout<<"yes";
    else
        cout<<"no";
    delete p;



    system("pause");
    return 0;
}
结果运行出错
0x00AA48CF 处的第一机会异常(在 ConsoleApplication2.exe 中): 0xC0000005: 读取位置 0x0029B000 时发生访问冲突。

调试后,在 char *p=new char[20];
就显示+        p    0xcccccccc <读取字符串的字符时出错。>    char *

希望大神帮忙解决


5 回复
#2
rjsp2013-10-24 09:35
'/0' 改为 '\0'

另外,你的代码实在太差了,有太多错误和恶习,等会儿帮你写一个
#3
rjsp2013-10-24 09:38
程序代码:
#include <string>
#include <iostream>
using namespace std;

bool judge( const std::string& s )
{
    for( size_t i=0; i<s.size()/2; ++i )
    {
        if( s[i] != s[s.size()-1-i] )
            return false;
    }
    return true;
}


int main()
{
    string s;
    getline( cin, s );

    cout << ( judge(s) ? "yes" : "no" ) << endl;

    return 0;
}
#4
blueskiner2013-10-24 13:01
程序代码:
#include <iostream>
using namespace std;
#include <string.h>

bool judge(char *p,int len)
{
    int start=0;
//    int end=0;
//     int i=0;
//     start=i;
//     while(p[i]!='/0')
//         i++;
//    end=i-1;
    while(start<len)
    {
        if(p[start]!=p[len-1])
            return false;
        start++;
        len--;   
    }
    return true;
}

int main(int argc, char** argv)
{
    char *p=new char[20];
    cin.getline(p,20);
    if(judge(p,strlen(p))==true)
        cout<<"yes";
    else
        cout<<"no";
    delete p;
    return 0;
}
#5
yhyoin2013-10-24 13:21
受教了,谢谢版主,我会注意的。

[ 本帖最后由 yhyoin 于 2013-10-24 13:33 编辑 ]
#6
ladododo2014-03-13 20:31
回复 2楼 rjsp
能帮我改一个么
1