2014-04-08 66 views
1

這實際上是我第一次在此網站上發佈。我遇到了使用ctsrings的問題。這個函數的目的是定義我自己的strcat函數版本。 我的代碼:C++運行時檢查失敗#2 - 變量'theArray'周圍的堆棧已損壞

void mystrcat(char destination[], const char source[]) 
{ 

    int i = 0; 
    while (destination[i] != '\0') 
    { 
     ++i; 
    } 

    int w = 0; 
    while (source[w] != '\0') 
    { 
     ++w; 
    } 

    int numOfElements = i; 
    int q = 0; 
    while (q < w) 
    { 
     destination[numOfElements] = source[q]; 
     ++q; 
     ++numOfElements; 
    } 

    i += q; 


    for (int c = 0; c < i; ++c) 
    { 
     cout << destination[c]; 
    } 


} 

出於某種原因,每當我跑我的程序隨機cstrings的兩種價格(例如,「cdvfvf」和「gfgfgd」),該程序會輸出正確的合併的答案,但權之後,它給了我陣列錯誤周圍的「損壞堆棧」。再一次,如果我對代碼的目的或問題的描述沒有意義,那真的很抱歉。並感謝任何迴應的人。

+1

「損壞的堆棧」意味着您寫入一個索引太遠,超過了數組的末尾97%的時間,以及3%寫入了索引-1。 Ergo「'destination [numOfElements] = source [q];'」是你的錯誤。 –

+0

顯示您調用該函數的部分程序。 –

+0

包含變量「theArray」的代碼部分將是相關的。 – molbdnilo

回答

1

我認爲問題是數組destination不足以存儲連接的字符串。

例如,對於這些字符串文字"cdvfvf""gfgfgd"目標數組的大小必須等於至少13

另外考慮到,這個循環後:

while (q < w) 
{ 
    destination[numOfElements] = source[q]; 
    ++q; 
    ++numOfElements; 
} 

應該有

destination[numOfElements] = '\0'; 
+0

好吧。我會嘗試一下 – user3512751

相關問題