0

この配列を並べ替えたいのですが、配列に特殊文字を含む文字列を入れないと、このコードは機能します。私が何かを持っているなら

!\ "#$%&'()* +、-./ 0123456789:; <=>?@

それは動作しません。VisualStudioでクラッシュします。

コードは次のとおりです。

#include <iostream>
#include <cstring>

using namespace std;

int main (){

    char data[10][40] = {     
      "",
      "Welcome",
      " !\"#$%&'()*+,-./0123456789:;<=>?@",
      "aBCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`",
      "abcdefghijklmnopqrstuvwxyZ{||||||||||}",
      "CD_ROM",
      "ROM",
      "SCS",
      "3.5 Floppi",
      ""
    };


    cout<<"Printing the array as is"<<endl<<endl;

    for (int i=0; i<10; i++){
            cout<<data[i]<<endl;
    }

    cout<<endl<<"Ordering the data in Alphabetical order"<<endl<<endl;


    // bubble sort

    for (int i=0 ; i<10-1 ; ++i) {
            char Tcopy[17];
            for (int j=i+1 ; j<10 ; ++j) {
                    if (strcmp(data[i], data[j]) > 0) {
                            strcpy(Tcopy, data[i]);
                            strcpy(data[i], data[j]);
                            strcpy(data[j], Tcopy);
                    }
            }
    }


    cout<<"Printing the array Sorted"<<endl<<endl;

    for (int i=0; i<10; i++){
            cout<<data[i]<<endl;
    }


// Pause
    cout<<endl<<endl<<endl<<"Please Close Console Window"<<endl;
    cin.ignore('\n', 1024);
    return(0);
}
4

1 に答える 1

1
char data[10][40]
…
char Tcopy[17];
…
strcpy(Tcopy, data[i]);

あなたの問題があります。配列Tcopyが短すぎます。(潜在的に)40文字を17文字の配列にコピーしています。バッファの終わりを上書きしているため、誰がどのような損害を被っているのかがわかります。

試す:

char Tcopy[40];
于 2012-06-18T20:57:37.597 に答える