I have an array which might contain empty/null positions (e.g: array[2]=3, array[4]=empty/unassigned). I want to check in a loop whether the array position is null.
array[4]==NULL //this doesn't work
I'm pretty new to C++.
Thanks.
Edit: Here's more code;
A header file contains the following declaration
int y[50];
The population of the array is done in another class,
geoGraph.y[x] = nums[x];
The array should be checked for null 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;
}
To check if an array is empty or not, you can use the . length property. The length property sets or returns the number of elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not.
The array can be checked if it is empty by using the array. length property. This property returns the number of elements in the array. If the number is greater than 0, it evaluates to true.
Use array::empty() method to check if the array is empty: The array::empty() is an inbuilt method in the C++ Standard template library that analyzes whether or not the defined array is blank. This technique does not change the elements of the array.
If your array is not initialized then it contains randoms values and cannot be checked !
To initialize your array with 0 values:
int array[5] = {0};
Then you can check if the value is 0:
array[4] == 0;
When you compare to NULL, it compares to 0 as the NULL is defined as integer value 0 or 0L.
If you have an array of pointers, better 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
You can use boost::optional
(or std::optional
since C++17), which was developed in particular for decision of 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]);
....
}
}
P.S. Do not use C-type array -> use std::array or std::vector.
std::array<int, 50> y; //not int y[50] !!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With