[英]Check array position for null/empty
我有一個可能包含空/空位置的數組(例如: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;
}
如果您的數組未初始化,則它包含隨機值且無法檢查!
用 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
如果數組包含整數,則該值不能為 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 是一個空指針常量!
您可以使用boost::optional
(或std::optional
用於較新版本),它是專門為確定您的問題而開發的:
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] !!!
在 C 編程中沒有對數組進行邊界檢查。 如果您將數組聲明為
int arr[50];
然后你甚至可以寫成
arr[51] = 10;
編譯器不會拋出錯誤。 希望這能回答你的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.