简体   繁体   English

C++ 初始化 bool 数组

[英]C++ initialize bool array

I use memset to initialize bool array.我使用 memset 来初始化 bool 数组。 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 :在 C++ 中,我们会使用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 .问题是sizeof(flag)不知道分配给指针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).指针的大小对于体系结构是固定的,这意味着只有动态数组的初始部分会被初始化(如果n很小,则会导致未定义的行为)。

If you insist on using "plain" array of bool , change the initialization code to this:如果您坚持使用bool “普通”数组,请将初始化代码更改为:

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 :更好的方法是使用std::vector<bool> ,它使用的实现与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.请注意,当您完成动态分配的数组时,使用std::vector<bool>使您不必调用delete[] flags

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 .数组项的大小是sizeof(bool)或等效的sizeof *flag ,数组的大小是n*sizeof(bool)n*sizeof *flag而不是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 ).sizeof flag很可能是 4(指针类型的大小),因此数组的 4 个项目被设置为0 ( false )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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