How do you initialise a dynamic array in C++?

前端 未结 10 2147
梦毁少年i
梦毁少年i 2020-11-27 13:27

How do I achieve the dynamic equivalent of this static array initialisation:

char c[2] = {};  // Sets all members to \'\\0\';

In other word

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-27 13:56

    Two ways:

    char *c = new char[length];
    std::fill(c, c + length, INITIAL_VALUE);
    // just this once, since it's char, you could use memset
    

    Or:

    std::vector c(length, INITIAL_VALUE);
    

    In my second way, the default second parameter is 0 already, so in your case it's unnecessary:

    std::vector c(length);
    

    [Edit: go vote for Fred's answer, char* c = new char[length]();]

提交回复
热议问题