2016-03-06 66 views
-1

我無法結束我的for循環。即使它看起來應該完成,它也會繼續。如何結束通過指針數組的循環

它通過一組指針數組,當最後一個指針返回時NULL它應該結束。但它仍在繼續。我覺得我錯過了一些相當簡單的事情。任何想法都表示讚賞。

#include "shape.h" 
#include <iostream> 
#include <string> 
#include <stdio.h> 


using namespace std; 

shape *getShape(); 

int main(){  
    shape *shape[10]; 

    for(int idx = 0; shape[idx] != NULL; ++idx) 
    {  
     shape[idx] = getShape();   
    } 

cout << "you made it!";  
    return (0); 
} 
+1

你很困惑C和C++。 – wildplasser

+0

getShape是做什麼的?它是否曾經返回NULL值? –

+0

for()'循環不知道'shape []'的大小是10,它只是繼續前進,直到找到一個NULL,如果你沒有放置一個它不會神奇地產生通過它自己。 C字符串是空終止的,數組不是。 – Havenard

回答

0

條件是每次運行前進行評估,因此代碼的前幾個部分展開了出來:

int idx = 0 ; 
while (1) 
{ 
    if (shape[idx] == NULL) break ; 
    shape[idx] = getShape() ; 
    ++idx ; 
    if (shape[idx] == NULL) break ; 
    shape[idx] = getShape() ; 
    ++idx ; 
    // and so on 
} 

我假設你想運行,直到getShape返回NULL,那麼試試這個:

int idx = -1 ; 
do 
{ 
    shape[++idx] = getShape() ; 
} while (shape[idx] != NULL) ; 

另外請注意,我假設額外的檢查,從你的例子樣品的目的是省略了,但我會提到,以防萬一,你應該始終總是總是檢查C-Array的末尾,以便您不會在分配給您的數組段後出現內存碎片。

編輯

我這裏還有額外的檢查,我說的是在一個更完整的代碼示例:

enum { 
    kArraySize = 10 
} ; 
shape* shapes[kArraySize] ; // note: named it "shapes" instead of "shape" to avoid a name collision 
int idx = -1 ; 
do 
{ 
    ++idx ; // *prepare* to go to the next index 
    if (idx >= kArraySize) // only need ==, but >= gives extra safety 
     break ; // stop before we go past the end of the array! 
    shapes[idx] = getShape() ; 
} while (shapes[idx] != NULL) ; 
+0

謝謝iAdjunct!這做到了。你是正確的,我現在看到我可能已經增加了更多的信息,但是這樣做很快。 對於getShape在完成作業後返回NULL,您是正確的。但我無法弄清楚如何通過這個結束循環。以上按預期工作。 它看起來像我混淆了我的語法。我以前試過一段時間循環,但它沒有按預期工作,這是因爲我沒有正確使用。 – Raxler

+0

你可以請擴展一個數組的檢查?對此我很陌生,對此我並不熟悉。我本來希望將它作爲一個動態創建的數組,但不是太確定,或者是否需要。但我想如果我這樣做了,我不需要檢查它,因爲它可能內置到動態創建中? – Raxler

+0

@Raxler - 請參閱編輯 – iAdjunct

-1

它不知道,如果形狀[10]爲NULL。它可能有一些內容,但尚未刪除。

試試這個:

shape *shape[n]; 

int lng = sizeof(shape)/sizeof(shape); 

for(int idx = 0; idx < lng; ++idx) 
{ 
    shape[idx] = getShape(); 
} 
+0

'形狀[10]'不存在,有效索引爲0到9 –

+1

確實形狀[10]存在!他從不說「停止如果我== 9」,他可以溢出陣列。你永遠不能確定,內存空間是NULL ... – FlowX

+0

綁定'10'的數組只有元素'0'到'9' –

0

for循環可以簡化爲...

for(int idx = 0; idx<10 && (shape[idx]=getShape()) != NULL; ++idx); 

您可以指定在同一語句進行比較。

您可能想要動態確定數組的大小,正如其他答案所建議的那樣。爲了簡單起見,我只是硬編碼了10。

對於這個特定的例子,最好只聲明一個常量來定義數組,然後在for循環條件中使用這個常量。