简体   繁体   中英

Sorting 2D array containing special characters C++

I would like to sort this array but this code works if I do not put any string with special characters in the array. If I have something like

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

it wont work. It crashes in Visual Studio.

Here is the code:

#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);
}
char data[10][40]
…
char Tcopy[17];
…
strcpy(Tcopy, data[i]);

There's your problem. Your Tcopy array is too short. You are copying (potentially) 40 characters into a 17-character array. You are overwriting the end of your buffer, resulting in who-knows-what damage.

Try:

char Tcopy[40];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM