how to initialize a char array?

前端 未结 8 1802
名媛妹妹
名媛妹妹 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 14:51

    This method uses the 'C' memset function, and is very fast (avoids a char-by-char loop).

    const uint size = 65546;
    char* msg = new char[size];
    memset(reinterpret_cast<void*>(msg), 0, size);
    
    0 讨论(0)
  • 2020-12-14 14:55

    The "most C++" way to do this would be to use std::fill.

    std::fill(msg, msg + 65546, 0);
    
    0 讨论(0)
  • 2020-12-14 15:05

    Absent a really good reason to do otherwise, I'd probably use:

    std::vector<char> msg(65546, '\0');
    
    0 讨论(0)
  • 2020-12-14 15:06

    The C-like method may not be as attractive as the other solutions to this question, but added here for completeness:

    You can initialise with NULLs like this:

    char msg[65536] = {0};
    

    Or to use zeros consider the following:

    char msg[65536] = {'0' another 65535 of these separated by comma};
    

    But do not try it as not possible, so use memset!

    In the second case, add the following after the memset if you want to use msg as a string.

    msg[65536 - 1] =  '\0'
    

    Answers to this question also provide further insight.

    0 讨论(0)
  • 2020-12-14 15:10

    You can use a for loop. but don't forget the last char must be a null character !

    char * msg = new char[65546];
    for(int i=0;i<65545;i++)
    {
        msg[i]='0';
    }
    msg[65545]='\0';
    
    0 讨论(0)
  • 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<char> 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.

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