简体   繁体   中英

C++ initialize bool array

I use memset to initialize bool array. But, the answer is not true. who can tell my the reason?

int countPrimes(int n) {
    bool *flag = new bool[n];
    int i, res = 0;
    memset(flag,false,sizeof(flag));
    for (i = 0 ; i<n ; i++) {

错误的输出

In C++ we'd use std::fill :

bool* flags = new bool[n];
std::fill(flags, flags+n, false); // Also works with `true`.

The problem is that sizeof(flag) has no idea about the size of the array allocated to the pointer flag . The size of the pointer is fixed for the architecture, meaning that only the initial part of the dynamic array would be initialized (or cause undefined behavior if n is small).

If you insist on using "plain" array of bool , change the initialization code to this:

memset(flags, false, sizeof(*flags)*n); // Wouldn't work with true

A better approach is to use std::vector<bool> , which uses an implementation that saves you a lot of memory compared to a "plain" array of bool :

int countPrimes(int n) {
    std::vector<bool> flag(n, false);
    int res = 0;
    for (int i = 0 ; i != n ; i++) {
        ...
    }
    return res;
}

Note that the use of std::vector<bool> frees you from having to call delete[] flags when you are done with the dynamically allocated array.

A size of the array item is sizeof(bool) or equivalent sizeof *flag , the size of the array is n*sizeof(bool) or n*sizeof *flag , not sizeof flag . The value sizeof flag is most likely 4 (a size of a pointer type), hence 4 items of your array got set to 0 ( false ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM