我在C中的程序有问题 . 我有一个模板类,它有一个函数bool,用于检查给定的单词或数组是否为回文结构 . 对于int和char everythig很好,程序生成“是”,但对于字符串程序启动但它给出
PK4_5.exe中0x534408DA(msvcr120d.dll)的第一次机会异常:0xC0000005:访问冲突读取位置0x00000003 . PK4_5.exe中0x534408DA(msvcr120d.dll)的未处理异常:0xC0000005:访问冲突读取位置0x00000003 .
这段代码有什么问题?
这是代码:
主功能:
#include "palindrom.h"
int main(){
int iTab[] = { 1, 2, 3, 2, 1 };
char cTab[] = "abcba";
string word ("aaaa");
palindrom<int> A;
palindrom<char> B;
palindrom<string> C;
if (A.palindrome(iTab, 5))
cout << "yes";
if (B.palindrome(cTab, strlen(cTab)))
cout << "yes";
if (C.palindrome(&word, word.length()))
cout << "yes";
return 0;
}
palindrom.h:
#pragma once
#include <iostream>
#include <string>
using namespace std;
template <typename T>
class palindrom
{
public:
bool palindrome(const T*x, int length);
palindrom();
~palindrom();
};
template <typename T>
bool palindrom<T>::palindrome(const T* x, int length){
for (int i = length / 2 - 1; i >= 0; i--)
if (x[i] != x[length - i - 1])
return false;
return true;
}
template <typename T>
palindrom<T>::palindrom(){}
template <typename T>
palindrom<T>::~palindrom(){}
palindrom.cpp是空的 .
2 回答
问题是你将想要创建回文的集合作为指针传递 . 这意味着,从
std::string
开始,您将其视为字符串数组,因此执行除x[0]
以外的任何操作都将导致未定义的行为 .而是将其作为非指针传递,并在需要时使用指针模板类型创建
palindrom
:这样,你就可以拥有
它也适用于
std::string
.将
if (C.palindrome(&word, word.length()))
更改为if (C.palindrome(word.c_str(), word.length()))
.另外,不要将
using namespace std;
放在头文件中,否则包含头文件的所有内容都将导入命名空间std,这可能不是所需的行为 .