13

我有一个可能包含空/空位置的数组(例如:array[2]=3,array[4]=empty/unassigned)。我想在循环中检查数组位置是否为空。

array[4]==NULL //this doesn't work

我对 C++ 很陌生。
谢谢。


编辑:这里有更多代码;头文件包含以下声明

int y[50];

数组的填充在另一个类中完成,

geoGraph.y[x] = nums[x];

应在以下代码中检查数组是否为空;

    int x=0;
    for(int i=0; i<sizeof(y);i++){
        //check for null
        p[i].SetPoint(Recto.Height()-x,y[i]);
        if(i>0){
            dc.MoveTo(p[i-1]);
            dc.LineTo(p[i]);

        }
        x+=50;
    }
4

4 回答 4

18

如果您的数组未初始化,则它包含随机值并且无法检查!

用 0 值初始化你的数组:

int array[5] = {0};

然后您可以检查该值是否为0:

array[4] == 0;

当您与 NULL 进行比较时,它与 0 进行比较,因为 NULL 被定义为整数值 0 或 0L。

如果您有一个指针数组,最好使用该nullptr值来检查:

char* array[5] = {nullptr}; // we defined an array of char*, initialized to nullptr

if (array[4] == nullptr)
    // do something
于 2013-10-02T08:05:52.527 回答
4

您可以使用boost::optional(或std::optional自 C++17 起),它是专门为解决您的问题而开发的:

boost::optional<int> y[50];
....
geoGraph.y[x] = nums[x];
....
const size_t size_y = sizeof(y)/sizeof(y[0]); //!!!! correct size of y!!!!
for(int i=0; i<size_y;i++){
   if(y[i]) { //check for null
      p[i].SetPoint(Recto.Height()-x,*y[i]);
      ....
   }
}

PS 不要使用 C 类型数组 -> 使用 std::array 或 std::vector。

std::array<int, 50> y;   //not int y[50] !!!
于 2013-10-02T08:55:46.137 回答
3

如果数组包含整数,则该值不能为 NULL。如果数组包含指针,则可以使用 NULL。

SomeClass* myArray[2];
myArray[0] = new SomeClass();
myArray[1] = NULL;

if (myArray[0] != NULL) { // this will be executed }
if (myArray[1] != NULL) { // this will NOT be executed }

正如http://en.cppreference.com/w/cpp/types/NULL所说,NULL 是一个空指针常量

于 2013-10-02T08:02:25.010 回答
0

在 C 编程中,数组中没有绑定检查。如果您将数组声明为

int arr[50];

然后你甚至可以写成

arr[51] = 10;

编译器不会抛出错误。希望这能回答你的问题。

于 2013-10-02T08:13:47.957 回答