对包含特殊字符的 2D 数组进行排序 C++

Sorting 2D array containing special characters C++

本文关键字:排序 C++ 数组 2D 包含 特殊字符      更新时间:2023-10-16

我想对这个数组进行排序,但是如果我不在数组中放置任何带有特殊字符的字符串,则此代码有效。如果我有类似的东西

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

它行不通。它在Visual Studio中崩溃。

这是代码:

#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]);

有你的问题。您的Tcopy数组太短。您正在将(可能)40 个字符复制到 17 个字符的数组中。您正在覆盖缓冲区的末尾,从而导致谁知道什么损坏。

尝试:

char Tcopy[40];