2017-01-10 120 views
-1

所以我得到這個編程入門任務,我必須寫一個程序,找到的第n個成員按以下順序1,121,1213121,121312141213121 ..等等。基本上,第一個成員是1,而下一個成員是[前一個成員] [前一個成員]。 N < 10.所以我得到了這個我不明白的問題,試圖在互聯網上搜索它,但沒有得到任何可以幫助我的東西。堆損壞檢測:普通塊(#176)後

#include "stdafx.h" 
#include <iostream> 

using namespace std; 

int size(int n, int realsize); 
int main() 
{ 
    int n; 
    cin >> n; 
    if (n == 1) { 
     cout << "1"; 
     return 0; 
    } 
    int helper = 0; 
    char c = '2'; 
    char* look; 
    char* say; 
    say = new char[size(n, 1) + 1](); 
    look = new char[size(n - 1, 1) + 1](); 
    look[0] = '1'; 
    while (helper < n) { 
     for (int i = 0; i < size(helper + 1, 1); i++) { 
      say[i] = look[i]; 
     } 
     say[size(helper + 1, 1)] = c; 
     for (int i = size(helper + 1, 1) + 1; i < size(helper + 1, 1) * 2 + 1; i++) { 
      say[i] = look[i - (size(helper + 1, 1) + 1)]; 
     } 
     for (int i = 0; i < size(helper + 1, 1) * 2 + 1; i++) { 
      look[i] = say[i]; 
     } 
     helper += 1; 
    } 
    cout << say; 
    delete[] say; 
    delete[] look; 
    return 0; 
} 

int size(int n, int realsize) 
{ 
    if (n == 1) 
     return realsize; 
    else 
     return size(n - 1, realsize * 2 + 1); 
} 
+0

***檢測到堆損壞:正常塊後***您最有可能超出一個或多個動態數組的範圍。 – drescherjm

+1

如果您使用'std :: vector '而不是動態分配,那麼您可以使用'at()'來表明您要超出數組範圍。 [見這裏](http://ideone.com/1tVUXC)。最後一個循環出現問題('look [i] = say [i];')。由於您似乎在使用Visual Studio,因此在出錯時應立即拋出「out_of_range」異常,而不是在程序終止時出現「堆損壞」錯誤, – PaulMcKenzie

回答

0

您正在覆蓋您的look變量的容量。它最終以say的全部內容編寫,因此它需要具有相同的大小。

雖然我不縱容下面的代碼爲好的代碼,它已經從自己的實現最低限度的調整,應該給出一個更堅實的基礎繼續努力工作的結果。我用第一個數字測試了它,但這並不能保證它是完美的。

#include <iostream> 

using namespace std; 

int size(int n, int realsize); 

int main() 
{ 
    int n; 
    cin >> n; 
    if (n == 1) 
    { 
     cout << "1"; 
     return 0; 
    } 
    int helper = 0; 
    char c = '2'; 
    char * look; 
    char * say; 
    say = new char[size(n, 1) + 1];  // Ditch the() call, which is confusing. 
    look = new char[size(n, 1) + 1]; // Make the same size as "say" 
    look[0] = '1'; 
    while (helper < n - 1) // You're overrunning this loop I think, so I did it to n - 1. 
    { 
     for (int i = 0; i < size(helper + 1, 1); i++) 
     { 
      say[i] = look[i]; 
     } 
     say[size(helper + 1, 1)] = c + helper; // You were adding '2' every time, so this will add 2, 3, 4, etc incrementally. 
     for (int i = size(helper + 1, 1) + 1; i < size(helper + 1, 1) * 2 + 1; i++) 
     { 
      say[i] = look[i - (size(helper + 1, 1) + 1)]; 
     } 
     for (int i = 0; i < size(helper + 1, 1) * 2 + 1; i++) 
     { 
      look[i] = say[i]; 
     } 
     helper += 1; 
    } 
    say[size(n, 1)] = '\0'; // Null-terminate "say" before printing it out. 
    cout << say; 
    delete[] say; 
    delete[] look; 
    return 0; 
} 

int size(int n, int realsize) 
{ 
    if (n == 1) 
     return realsize; 
    else 
     return size(n - 1, realsize * 2 + 1); 
} 
+0

非常感謝!我修好了,它通過了我教授的測試。 :) –

+0

選擇它作爲答案呢? :) – Mitch

+0

我不知道如何,但我想我做到了:)。感謝幫助隊友! –