2013-12-21 18 views
0

我試圖採取以下輸入:當使用scanf函數/ CIN,程序運行在調試模式很好,但給了運行時錯誤

1 
4 
47 2 4 43577 

我的代碼與此交易的組成部分是:

for (scanf("%d", &t); t --;) 
{ 
    int count = 0; 
    scanf("%d",&n); 

    for (int i = 0, x; i < n; ++ i) 
    { 
     scanf("%d",&x); 
     str = to_string(x); 
     f4[i] = get_count(str,'4'); 
     f7[i] = get_count(str,'7'); 
    } 

但是,我得到一個運行時錯誤,它顯示文件free.c中的訪問衝突。

但是,當我嘗試調試它時,它在調試模式下運行良好,並給出了正確的答案。

此外,當我輸入變量x後,我輸入它,該程序以及運行時良好。這顯示在以下代碼中,該代碼在運行時也運行正常:

for (scanf("%d", &t); t --;) 
{ 
    int count = 0; 
    scanf("%d",&n); 

    for (int i = 0, x; i < n; ++ i) 
    { 
     scanf("%d",&x); 
     cout<<"A"<<i<<" is "<<x<<'\n'; 
     str = to_string(x); 
     f4[i] = get_count(str,'4'); 
     f7[i] = get_count(str,'7'); 
    } 

任何想法爲什麼會發生這種情況?

一些stackoverflow用戶說,代碼運行良好。我正在使用VS 2012.可以這是編譯器特定的東西嗎?

的完整代碼:

#include<iostream> 
#include<conio.h> 
#include<string> 
#include<math.h> 

using namespace std; 

int get_count(string s, char x) 
{ 
    int count = 0; 
    int l = s.length(); 
    for(int i = 0; i < l;i++) 
    { 
    if (s[i] == x) 
     count++; 
    } 

    return count; 
} 

void main() 
{ 

int * f4 = new int; 
int * f7 = new int; 
string * back = new string; 

int n = 0; 
int t = 0; 

string str; 

for (scanf("%d", &t); t --;) 
{ 
    int count = 0; 
    scanf("%d",&n); 

    for (int i = 0, x; i < n; ++ i) 
    { 
     scanf("%d",&x); 
     str = to_string(x); 
     f4[i] = get_count(str,'4'); 
     f7[i] = get_count(str,'7'); 
    } 

    for(int i = 0;i < n;i++) 
    { 
     for(int j = i; j < n;j++) 
     { 
      int c4 = 0; 
      int c7 = 0; 
      for(int k = i; k <= j;k++) 
      { 
       c4 += f4[k]; 
       c7 += f7[k]; 
      } 
      double value = pow((double)c4,(double)c7); 

      if(value <= (double)(j - i + 1)&&(c4!=2)&&(c7!=2)) 
      { 
       count++; 
       //cout<<"yes"<<'\t'; 
      } 

     } 
    } 

    cout<<"Ans: "<<count<<'\n'; 
} 
//getch(); 
} 

有除了那些在此代碼沒有其他變量賦值。

,我和運行時得到確切的錯誤是:

Unhandled exception at 0x7794E3BE (ntdll.dll) in Practice1.exe: 0xC0000005: Access violation reading location 0x38389246. 
+1

可以包含錯誤信息? – unekwu

+0

通常,如果在調試器外部運行它時出現故障,但不在調試器內部出現故障,那麼您不會爲其中一個變量分配內存 - 在調試器中它有時會起作用 - 我們需要了解如何聲明變量。 –

+0

從你的描述中你很可能會調用* undefined behavior *。 –

回答

0

您不包括「get_count」功能。我認爲這與該功能有關。我重寫了該函數返回一些數字,我沒有得到這個錯誤。試着斷言你不是試圖在該函數中使用空指針。 工作正常我的機器上: 這是我改變

for (int i = 0, x; i < n; ++ i) 
{ 
    scanf("%d",&x); 
    stringstream ss; 
    ss << x; 
    str = ss.str(); 
    f4[i] = get_count(str,'4'); 
    f7[i] = get_count(str,'7'); 
} 

輸出:

1 
4 
47 2 4 43577 
Ans: 5 
+0

我試着做你的建議。我沒有調用函數get_count,而是給f4 []和f7 []分配一個數字,但我們遇到了同樣的問題。我已經包括了一切,請看看。 – user3124696

+0

你的代碼似乎在我的機器上運行良好。我沒有C++ 11,所以我不得不修改你的代碼來使用stringstream而不是to_string()。我不知道這是從哪裏來的錯誤。 – unekwu

+0

謝謝,但你的黑客並沒有解決問題。我試過你的方式,而不是使用to_string,我也試圖用itoa來做到這一點。我甚至改變了我的get_count,這樣我就不會在程序中涉及字符串或字符數組了! – user3124696

相關問題