2017-02-20 54 views
1

为什么我的静态布尔数组未正确初始化?只有第一个被初始化 - 我怀疑这是因为数组是静态的。静态Bool数组未初始化为集

下面的MWE是用GCC编译的,它基于一个函数,我写这个函数是为了说明我的问题而转入主程序。我曾尝试使用和不使用C++ 11。我的理解是因为这个数组是静态的,并且初始化为true,所以当我第一次进入我的函数时应该总是打印。所以在这个MWE中它应该打印一次。

#include <iostream> 

using namespace std; 

const int arraysize = 10; 
const int myIndex = 1; 

static bool firstTimeOverall = true; 

int main() 
{ 
    static bool firstCloudForThisClient[arraysize] = {true}; 
    cout.flush(); 
    if (firstCloudForThisClient[myIndex]) 
    { 
     cout << "I never get here" << endl; 
     firstCloudForThisClient[myIndex] = false; 
     if (firstTimeOverall) 
     { 
      firstTimeOverall = false; 
      cout << "But think I would get here if I got in above" << endl; 
     } 
    } 
    return 0; 
} 
+1

是什么让你认为firstCloudForThisClient'的'所有元素都被初始化为'真'? – quamrana

回答

1

您可能需要反转的条件,利用缺省初始化的:

#include <iostream> 

using namespace std; 

const int arraysize = 10; 
const int myIndex = 1; // note this index does not access the first element of arrays 

static bool firstTimeOverall = true; 

int main() 
{ 
    static bool firstCloudForThisClient[arraysize] = {}; // default initialise 
    cout.flush(); 
    if (!firstCloudForThisClient[myIndex]) 
    { 
     cout << "I never get here" << endl; 
     firstCloudForThisClient[myIndex] = true; // Mark used indexes with true 
     if (firstTimeOverall) 
     { 
      firstTimeOverall = false; 
      cout << "But think I would get here if I got in above" << endl; 
     } 
    } 
    return 0; 
} 
0

你正在使用array[size] = {true}阵列上初始化仅第一元件,如果ARRAYSIZE变量是更大然后如图1所示,其它元素的初始值取决于平台。我认为这是一个未定义的行为。

如果你真的需要初始化你的阵列,使用循环代替:

for(int i=0; i < arraysize; ++i) 
firstCloudForThisClient[i] = true; 
+0

因为这是一个用于被多次调用的函数的静态变量,所以我不能使用循环 - 这是否意味着我应该将此函数转换为对象? – user3235290

+1

是的,将此功能转换为对象可能有用。或者您可以将此循环移入其他函数并调用一次,例如在程序开始时。如果你非常喜欢静态变量,你甚至可以创建一个静态布尔标志,这将保护你再次启动数组。 –

+0

感谢您的建议 - 我playinf试图获得一些更复杂的线程代码,使用点云库的功能。出于这个原因,我现在会采纳你的后一个建议,并在以后把你以前的建议(把它变成一个对象)。谢谢! – user3235290

1
static bool firstCloudForThisClient[arraysize] = {true}; 

这初始化第一个条目是真的,其他所有条目都是假的。

if (firstCloudForThisClient[myIndex]) 

然而,由于myIndex是1和数组索引是基于零的,这个访问第二条目,这是错误的。

0

你应该访问数组的第一个元素,以便使用:

const int myIndex = 0;