#33209: 我一直記憶體區段錯誤! Segmentation fault (core dumped)但我不知道要怎麼解決,而且debug後也不知道是哪裡出錯,希望有人可以幫我點出來,謝謝


ss810007@sish.ntpc.edu.tw (高三智05吳政頡)

學校 : 不指定學校
編號 : 217459
來源 : [140.138.241.165]
最後登入時間 :
2022-12-13 12:59:47
d492. 10226 - Hardwood species -- UVa10226 | From: [60.251.127.173] | 發表日期 : 2022-12-11 10:36

 

#include <iostream>
#include<string>
#include<algorithm>
#include<iomanip>
using namespace std;

int main()
{
    double n;
    while (cin >> n) {
        string s, space;
        cin.ignore();
        getline(cin, space);
        if (space == "") {
        }
        for (int i = 0; i < n; i++) {
            string arr[10000];
            double arr2[10000]{};
            int t = 0;
            for (int j = 0;; j++) {
                getline(cin, s);
                if (s == "") {
                    break;
                }
                arr[j] = s;
                t = j;
            }
            sort(arr, arr + t + 1);
            float counter = 1.0;
            for (int k = 0; k <= t; k++) {
                if (arr[k] == "0" || arr[k] == "") {
                    continue;
                }
                else {
                    for (int l = k + 1; l <= t; l++) {
                        if (arr[k] == arr[l]) {
                            arr[l] = "0";
                            counter++;
                        }
                    }
                    arr2[k] = counter;
                    counter = 1.0;
                }
            }
            double sum = t + 1;
            for (int k = 0; k <= t; k++) {
                if (arr[k] != "0") {
                    cout << arr[k] << " " << fixed << setprecision(4) << arr2[k] / sum * 100 << endl;
                }
            }
            cout << endl;
        }
    }
}

如果把我的arr[10000]改成arr[1000000]就堆疊但我也不知道是哪堆疊。。。

 
#33264: Re: 我一直記憶體區段錯誤! Segmentation fault (core dumped)但我不知道要怎麼解決,而且debug後也不知道是哪裡出錯,希望有人可以幫我點出來,謝謝


cges30901 (cges30901)

學校 : 不指定學校
編號 : 30877
來源 : [101.136.203.77]
最後登入時間 :
2024-04-07 15:34:14
d492. 10226 - Hardwood species -- UVa10226 | From: [101.137.191.22] | 發表日期 : 2022-12-17 19:33

1.

            string arr[10000];
            double arr2[10000]{};
2.
                        if (arr[k] == arr[l]) {
                            arr[l] = "0";
                            counter++;
                        }

  1. 可以改用vector,動態記憶體應該也可以
  2. 1改好後還是會TLE,可以在if後面加個else break,勉強能1.9s AC
 
ZeroJudge Forum