Check array location for null / empty

I have an array that can contain empty / zero positions (for example: array [2] = 3, array [4] = empty / unassigned). I want to check in a loop whether the position of the array is zero.

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

I am new to C ++.
Thanks.


Edit: here is more code; The header file contains the following declaration

 int y[50]; 

The population of the array is in another class,

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

The array should be checked for zero in the following code;

  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; } 
+7
c ++ arrays null
source share
4 answers

If your array is not initialized, it contains the values โ€‹โ€‹of randoms and cannot be verified!

To initialize an array using 0 values:

 int array[5] = {0}; 

Then you can check if the value is 0:

 array[4] == 0; 

When you compare with NULL, it compares with 0, because NULL is defined as an integer value of 0 or 0L.

If you have an array of pointers, it is best to use the nullptr value to check:

 char* array[5] = {nullptr}; // we defined an array of char*, initialized to nullptr if (array[4] == nullptr) // do something 
+11
source share

If the array contains integers, the value cannot be NULL. NULL can be used if the array contains pointers.

 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 } 

Like http://en.cppreference.com/w/cpp/types/NULL , NULL is a null pointer constant!

+3
source share

You can use boost :: optional ( optional ), which was developed, in particular, to solve your problem:

 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 Do not use a C-type array -> use std :: array or std :: vector:

 std::array<int, 50> y; //not int y[50] !!! 
+2
source share

In C, an unrelated check is programmed. If you declare an array as

 int arr[50]; 

Then you can even write like

 arr[51] = 10; 

The compiler will not throw an error. Hope this answers your question.

+1
source share

All Articles