无法在 C++ 中删除 char 指针
Can not delete char pointer in C++
为什么我不能执行以下行?
delete [] target;
就我而言?
代码如下:
main.cpp
#include <iostream>
using namespace std;
#include "Char.h"
int main()
{
char * text = "qwerty";
char * a = new char[charlen(text)+1];
copyon(a,text);
cout<<a<<endl;
char * test = "asdfghjkl";
assign(&a, test);
assign(&a, a);
char * test1 = new char[26];
for (int i(0); i < 26; i++)
{
test1[i] = char(i+65);
}
test1[26] = '[=11=]';
anotherAssign(test1, a);
cout << test1 << endl;
return 0;
}
Char.cpp
#include "Char.h"
#include <iostream>
#include <cassert>
#include <cstring>
size_t charlen(const char * ps)
{
size_t len=0;
while (ps[len++]);
assert(len-1==strlen(ps));
return len;
}
void assign(char** target, const char* source)
{
if (*target==source)
return;
delete [] *target;
*target = new char[charlen(source)+1];
copyon(*target, source);
return;
}
void anotherAssign(char* target, const char* source)
{
if (target==source)
return;
delete [] target;
target = new char[charlen(source)+1];
copyon(target, source);
return;
}
void copyon(char* const target, const char* const source)
{
char * t = target;
const char * s = source;
while (*t++ = *s++);
//while(*target++ = *source++)
// ;
std::cout << target << " source = " << source << std::endl;
return;
size_t len = charlen(source);
//for (size_t i=0; i<len; ++i)
// target[i]=source[i];
//target[len]='[=12=]';
}
这里有一个例外:
如果你这样做:
char * test1 = new char[26];
那么你的数组将从 test1[0]
变为 test1[25]
。
这意味着:
test1[26] = '[=11=]';
超出范围。此时,头部已损坏,接下来发生的事情是未定义的(但很少需要)。
为什么我不能执行以下行?
delete [] target;
就我而言?
代码如下:
main.cpp
#include <iostream>
using namespace std;
#include "Char.h"
int main()
{
char * text = "qwerty";
char * a = new char[charlen(text)+1];
copyon(a,text);
cout<<a<<endl;
char * test = "asdfghjkl";
assign(&a, test);
assign(&a, a);
char * test1 = new char[26];
for (int i(0); i < 26; i++)
{
test1[i] = char(i+65);
}
test1[26] = '[=11=]';
anotherAssign(test1, a);
cout << test1 << endl;
return 0;
}
Char.cpp
#include "Char.h"
#include <iostream>
#include <cassert>
#include <cstring>
size_t charlen(const char * ps)
{
size_t len=0;
while (ps[len++]);
assert(len-1==strlen(ps));
return len;
}
void assign(char** target, const char* source)
{
if (*target==source)
return;
delete [] *target;
*target = new char[charlen(source)+1];
copyon(*target, source);
return;
}
void anotherAssign(char* target, const char* source)
{
if (target==source)
return;
delete [] target;
target = new char[charlen(source)+1];
copyon(target, source);
return;
}
void copyon(char* const target, const char* const source)
{
char * t = target;
const char * s = source;
while (*t++ = *s++);
//while(*target++ = *source++)
// ;
std::cout << target << " source = " << source << std::endl;
return;
size_t len = charlen(source);
//for (size_t i=0; i<len; ++i)
// target[i]=source[i];
//target[len]='[=12=]';
}
这里有一个例外:
如果你这样做:
char * test1 = new char[26];
那么你的数组将从 test1[0]
变为 test1[25]
。
这意味着:
test1[26] = '[=11=]';
超出范围。此时,头部已损坏,接下来发生的事情是未定义的(但很少需要)。