错误的内存分配新字符 [N]
wrong memory allocation new char [n]
这个程序有什么问题?
#include<iostream>
using namespace std;
void main()
{
int n = 5;
char* p = new char [n];
int i;
for(i=0;i<n;i++)
{
p[i] = 'A'+i;
}
cout<<p<<endl;
}
为什么我得到"ABCDExxxx"而不是"ABCDE"?内存分配有什么问题?
内存分配没有任何问题,只是内存永远不会释放。不要忘记在main
返回之前delete [] p;
。
输出的问题是p
指向的字符串没有终止' '
。通常,您应该为数组分配一个空间,至少比要放入数组中的字符多一个字符,并在最后一个字符之后放置一个' '
。当然,更好的解决方案是使用 std::string
,它会为您处理所有这些问题。
C 字符串需要以 null 结尾。 再添加一个包含 0 的字节。
您可以使用
new
为char
分配存储空间 这样就可以了。但是,如果您稍后打算将其与与空终止字符相关的函数一起使用(例如strlen
,即或将其打印出来),那么在为char*
分配存储时,您需要分配字符数 + 1 更多来存储