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

前端 未结 6 1336
迷失自我
迷失自我 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:07

    The first allocates an array of 10 char's. The second allocates one char initialized to 10.

    Or:

    The first should be replaced with std::vector<char>, the second should be placed into a smart pointer.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-05 00:20
    char *a = new char[10];
    ...
    delete [] a;
    

    The above dynamically allocates and deallocates 10 contiguous memory slots that can be used to store chars.

    char *a = new char(10);
    ...
    delete a;
    

    The above dynamically allocates and deallocates one memory slot that is initialized with the integer value 10, equivalent to the char value '\n'.


    Do NOT use the std::vector<T> if you do not first understand pointers. Knowing how memory allocation and pointers work will make you a better programmer.

    0 讨论(0)
  • 2020-12-05 00:22
    new char[10];
    

    dynamically allocates a char[10] (array of char, length 10), with indeterminate values, while

    new char(10);
    

    again, dynamically allocates a single char, with an integer value of 10.

    0 讨论(0)
  • 2020-12-05 00:24

    Well the first one will make an array. But i guess your question is mostly on the second one. Your code can use it as a valid character, consider:

    char * x ;
    cin >> *(x=new char()) ;
    

    Will make a character dynamically and then read it from stdin.

    0 讨论(0)
  • 2020-12-05 00:31

    [10] defines an array where as (10) assigns a value to the newly created (single) character.

    If you want to declare an array of size 10 in C and by mistake you define char a(10), compiler would throw a syntax error, so you get to fix it. But in C++, it will compile fine and your program may crash while accessing say a[1] or while deleting a.

    So in C++, its always better to use vector rather than dynamically allocated arrays. I hope you got the point.

    0 讨论(0)
提交回复
热议问题