奇怪的问题,关于逆置句子中的字符串,有时候能运行,有时又出问题。
//大家帮我看看代码
#include <iostream>
using namespace std;
int getNumber(char* p,char* q)
{
if (p> q)
{
return (int)(p-q);
}
else
{
return (int)(-1*(p-q));
}
}
void coutChars(char* p,char* q)
{
int temp1 = getNumber(p,q);
for (int i=0;i <=temp1;i++)
{
cout < <*p;
p++;
}
};
int main()
{
char input = ' ',*p=NULL,*q=NULL,*temp=NULL,*firstAddr=NULL;
p = new char( 'a ');
int charCount = 0;
while (input!= '! ')
{
cin.get(input);
*p = input;
p++;
charCount++;
}
q=p;
firstAddr = p -charCount;
for (int i=0;i <=charCount;i++)
{
q--;
if (*q== ' ')
{
temp = q;
coutChars(temp+1,p);
cout < <endl;
p=q;
}
}
p=q=firstAddr;
bool tag = true;
while (tag)
{
q++;
if (*q== ' ')
{
coutChars(p,q-1);
tag= false;
}
}
cout < <endl;
p=q=temp=firstAddr;
return 0;
}
[解决办法]
p = new char( 'a ');
==========
只分配了一个字符的内存空间!, 以后的p++都是非法的!