What's the difference between new char[10] and new char(10)

前端 未结 6 1430
迷失自我
迷失自我 2020-12-05 00:06

In C++, what\'s the difference between

char *a = new char[10];

and

char *a = new char(10);

Thanks!

6条回答
  •  广开言路
    2020-12-05 00:13

    I would rather use:

    size_t size = 10; //or any other size
    std::string buff(size, 0); //or: std::string buff(size, '\0');
    

    Now if you must use the char* buff, then you can use:

    &buff[0]
    

    When you need to use const char* then you can use:

    buff.c_str()
    

    The big advantage is that you don't need to deallocate the memory, stl take care of this for you. The next advantage is that you can use all of the stl string functions

提交回复
热议问题