C++ 使用指针时调试断言失败
我正试图更好地理解指针,并且很难找出代码导致调试断言失败的原因。 当我注释掉“while(*neu++=*s++)”,然后在“strcopy(neu,s);”中注释时,效果很好。他们不应该这样做吗C++ 使用指针时调试断言失败,c++,debugging,pointers,C++,Debugging,Pointers,我正试图更好地理解指针,并且很难找出代码导致调试断言失败的原因。 当我注释掉“while(*neu++=*s++)”,然后在“strcopy(neu,s);”中注释时,效果很好。他们不应该这样做吗 #include <iostream> #include <cstring> using namespace std; void strcopy(char* ziel, const char* quelle) { while (*ziel++ = *quelle++
#include <iostream>
#include <cstring>
using namespace std;
void strcopy(char* ziel, const char* quelle)
{
while (*ziel++ = *quelle++);
}
char* strdupl(const char* s)
{
char *neu = new char[strlen(s) + 1];
while (*neu++ = *s++);
//strcopy(neu, s);
return neu;
}
int main()
{
const char *const original = "have fun";
cout << original << endl;
char *cpy = strdupl(original);
cout << cpy << endl;
delete[] cpy;
return 0;
}
#包括
#包括
使用名称空间std;
无效结构副本(char*ziel,const char*quelle)
{
而(*ziel++=*quelle++);
}
字符*strdull(常量字符*s)
{
char*neu=新字符[strlen(s)+1];
而(*neu++=*s++);
//strcopy(neu,s);
返回neu;
}
int main()
{
const char*const original=“玩得开心”;
coutstrcopy
获取指针neu
的副本,因此在返回字符串时,neu
仍然指向字符串的开头。使用strdup1
中的while循环,您在返回它之前正在修改neu
。在此指针上调用delete
会导致失败,因为它不同从以前的新的'd
解决方案是使用临时变量在字符串上递增和复制
char *neu = ...
char *tmp = neu;
while (*tmp++ = *s++);
return neu;