how to initialize a char array?

前端 未结 8 1833
名媛妹妹
名媛妹妹 2020-12-14 14:39
char * msg = new char[65546];

want to initialize to 0 for all of them. what is the best way to do this in C++?

8条回答
  •  不思量自难忘°
    2020-12-14 15:11

    what is the best way to do this in C++?

    Because you asked it this way:

    std::string msg(65546, 0); // all characters will be set to 0
    

    Or:

    std::vector msg(65546); // all characters will be initialized to 0
    

    If you are working with C functions which accept char* or const char*, then you can do:

    some_c_function(&msg[0]);
    

    You can also use the c_str() method on std::string if it accepts const char* or data().

    The benefit of this approach is that you can do everything you want to do with a dynamically allocating char buffer but more safely, flexibly, and sometimes even more efficiently (avoiding the need to recompute string length linearly, e.g.). Best of all, you don't have to free the memory allocated manually, as the destructor will do this for you.

提交回复
热议问题