对包含特殊字符的 2D 数组进行排序 C++
Sorting 2D array containing special characters C++
我想对这个数组进行排序,但是如果我不在数组中放置任何带有特殊字符的字符串,则此代码有效。如果我有类似的东西
!\"#$%&'()*+,-./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];
相关文章:
- 二叉排序树无法编译
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- C++选择排序算法中的逻辑错误
- 使用C++程序合并排序没有得到正确的输出
- 计算排序向量的向量中唯一值的计数
- 排序算法c++
- 使用2个键的cpp-stl::优先级队列排序不正确
- 将结构向量排序为子组
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 如何对点云数据进行排序
- 对字符串进行排序时,在c++中处理sort()
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- 下面是排序算法O(n)吗
- std::sort()函数无法对向量的一部分进行排序
- shell排序中的交换和比较
- clang格式:禁用排序包含
- 显示错误输出的简单数组排序程序
- 为什么我的排序算法会更改数组值
- 试图在c++中对数字列表进行排序
- 如何在C++中对数组进行冒泡排序