不多说,直接上代码,看大家是否很快就能发现问题:
#include#include #include #define MaxLine 500 #define isblank(ch) ((ch==' ')||(ch=='n')) using namespace std; char* trim(char* str) { char* p; char buff[MaxLine]; int len = strlen(str) + 1; strcpy_s(buff, MaxLine, str); p = buff + strlen(buff) - 1; while (isblank(*p))p--; p++; *p = 0; p = buff; while (isblank(*p))p++; strcpy_s(str, len, p); return p; } int main() { char* p; char sInf[] = " Hello,world!n "; p = trim(sInf); printf("sInf:n%sn", sInf); printf("p:n%s", p); return 0; }
我们来看运行结果:
可以看到p的输出存在乱码,并且这个乱码还非常随机。
错误原因就是因为C++的函数返回的指针指向的内存在在函数运行结束后随着堆栈释放而破坏了,而Python则不会存在这个问题。
将上述代码的main函数改成如下:
int main()
{
char sInf[] = " Hello,world!n ";
char sRetBuf[MaxLine];
strcpy_s(sRetBuf,MaxLine,trim(sInf));
printf("sInf:n%sn", sInf);
printf("sRetBuf:n%s", sRetBuf);
return 0;
}
则执行就正常了:



