2015-02-03 2 views
-3

문제 :
"maxPrint"가 아무데도 0으로 재설정됩니다. 함수 "skaitymas"에서는 if를 따르고 가장 큰 것을 찾는 "p"로 변경됩니다. 함수가 완료되면갑작스러운 변수 재설정

, "maxPrint는"갑자기 다시 0이 ... maxPrint 심지어 그 후 임의의 장소에서 사용하지 않는 .. 당신이 범위를 벗어 SK에 액세스하는이 루프에서

#include <iostream> 
#include <fstream> 
#include <iomanip> 

using namespace std; 
const char duomF[] = "1.txt"; 
const char rezF[] = "rez1.txt"; 
const int CMax = 81; 

void reset(int SK[]) 
{ 
    for (int i = 0; i < CMax; i++) 
    { 
     SK[i] = 0; 
    } 
} 

void skaitymas(int SK[], int &n, int &maxPrint) 
{ 
    ifstream df(duomF); 
    char temp; 
    int tempsk; 
    int p; 

    df >> n; 
    for (int i = 0; i < n; i++) 
    { 
     df >> p; 
     if (p > maxPrint) 
     { 
      maxPrint = p; 
     } 
     cout << p << " " << maxPrint << endl; 
     for (int j = CMax - p; j < CMax; j++) 
     { 
      df >> temp; 

      { if (temp == '0') tempsk = 0; 
      else if (temp == '1') tempsk = 1; 
      else if (temp == '2') tempsk = 2; 
      else if (temp == '3') tempsk = 3; 
      else if (temp == '4') tempsk = 4; 
      else if (temp == '5') tempsk = 5; 
      else if (temp == '6') tempsk = 6; 
      else if (temp == '7') tempsk = 7; 
      else if (temp == '8') tempsk = 8; 
      else if (temp == '9') tempsk = 9; 
      } 

      SK[j] += tempsk; 
     } 
    } 
    df.close(); 
} 

void skaiciavimas(int SK[]) 
{ 
    int temp; 
    for (int i = CMax; i >= 0; i--) 
    { 
     if(SK[i] >= 10) 
     { 
      temp = SK[i]/10; 
      SK[i-1] += temp; 
      SK[i] = SK[i] % 10; 
     } 
    } 
} 

int main() 
{ 
    int SK[CMax]; 
    int n; int maxPrint = 0; 

    reset(SK); 
    skaitymas(SK, n, maxPrint); 
    skaiciavimas(SK); 


    for (int i = CMax - (maxPrint - 1); i < CMax; i++) cout << SK[i] << " "; 
    cout << maxPrint << endl; 

    ofstream rf(rezF); 
    for (int i = CMax - (maxPrint - 1); i < CMax; i++) rf << SK[i]; 
    rf.close(); 

    return 0; 

} 

답변

5

:

액세스 마찬가지로 SK 유효 지수 CMax - 10 출신
void skaiciavimas(int SK[]) 
{ 
    int temp; 
    for (int i = CMax; i >= 0; i--) 
    { 
     if(SK[i] >= 10)   //<<< BUG (i = CMax) 
     { 
      temp = SK[i]/10;  //<<< BUG (i = CMax) 
      SK[i-1] += temp;  //<<< BUG (i = 0) 
      SK[i] = SK[i] % 10; //<<< BUG (i = CMax) 
     } 
    } 
} 

참고 따라서 정의되지 않은 동작에 SK[CMax] 결과 액세스.

범위를 벗어난 배열에 쓸 때 주변 변수를 덮어 쓸 수 있습니다 (예 : maxPrint의 예기치 않은 수정을 설명 할 수 있음). 그러나 정의되지 않은 동작의 경우와 마찬가지로 문자 그대로 아무 것도 발생할 수 있습니다. 코드가되어 있는지 모른 채

내가 단지 아마 당신의 루프가되어야한다고 추측 할 수 일을 :

for (int i = CMax - 1; i > 0; i--) 
+3

네를. 정의되지 않은 동작입니다. 운 좋게도 어떤 고양이도 불을 지르지 않았습니다. 이 시간. – Zeta

+0

나는이 변수가 어떻게 거기에 영향을 미치는지 알지 못한다; ...; 하지만 고마워. 이제 작동합니다. – xTheEc0

+1

@ xTheEc0 : 편집 참조 - 범위를 벗어난 배열에 쓸 때 인접 변수를 잘 덮어 쓸 수 있습니다. –