错误的内存分配新字符 [N]

wrong memory allocation new char [n]

本文关键字:字符 内存 分配 新字符 错误      更新时间:2023-10-16

这个程序有什么问题?

#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 的字节。

您可以使用

newchar分配存储空间 这样就可以了。但是,如果您稍后打算将其与与空终止字符相关的函数一起使用(例如strlen,即或将其打印出来),那么在为char*分配存储时,您需要分配字符数 + 1 更多来存储。C 字符串需要以 null 结尾。

为什么我得到"ABCDExxxx"而不是"ABCDE"?有什么问题 内存分配?

您的数据不是以 null 结尾的(末尾不包含 '',因此您将打印垃圾,直到在其他地方找到字符 '')。要使其按预期工作,您可以执行以下操作:

int n = 5;
char* p = new char [n+1];
p[n]='';
for(i=0;i<n;i++)
{
    p[i] = 'A'+i;
         ^
        side note: this is OK, however if your p has been pointing to a string 
        literal, i.e. if it was defined as  char*p = "string literaln";
        then according to section 2.14.5 paragraph 11 of the C++ standard,
        it would invoke undefined behavior:
        The effect of attempting to modify a string literal is undefined.
        so be aware :p !
}
cout<<p<<endl;

请记住使用

delete [] p;

正如其他人评论的那样,改用std::string可能是一个更好的主意。

首先,当你已经在C++

请改用std::string

它有一个成员函数c_str(),有助于使用 C api/函数


#include<iostream>
using namespace std;
int main()
^^ main should return int
{
    int n = 5;
   //C string needs to be null terminated, so an extra
    char* p = new char [n+1];
    int i;
    for(i=0;i<n;i++)
    {
        p[i] = 'A'+i;
    }
    p[i] = ''; //Insert the null character
    cout<<p<<endl;
}

你只是没有放置一个空字符。使用此代码:

#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;
}

当您使用 c++ 时,我建议使用 std::string .

#include<iostream>
#include<string>
        using namespace std;
        void main()
        {
            //int n = 5;
            //char* p = new char [n];
            string s;
            int i;
            for(i=0;i<n;i++)
            {
                s.append("/*whatever string you want to append*/");
            }
            cout<<s<<endl;
        }

当endl遇到'\0'时,它会返回,所以如果你在char[]中没有'\0',直到找到它,它才会继续读取记忆。