アプリ版:「スタンプのみでお礼する」機能のリリースについて

#include<iostream>

using namespace std;

const int R_SIZE = 5;
const int C_SIZE = 17;

void selectionSort(char ary[][C_SIZE]);
void printArray(char ary[][C_SIZE]);

int main(){
char names[R_SIZE][C_SIZE] = { "Collins, Bill",
"Smithm, Bart",
"Allen, Jim",
"Griffin, Jim",
"Stamey, Marty"};

selectionSort(names);

cout << "Sorted array is:" << endl << endl;
printArray(names);

return 0;
}//end main()

//*********************************************
void selectionSort(char ary[][C_SIZE]){
int minIndex;
char minValue[R_SIZE];

for(int ix = 0; ix < R_SIZE - 1; ix++)
{
minIndex = ix;
strcpy(minValue, ary[ix]);

for(int jx = ix + 1; jx < R_SIZE; jx++)
{
if(ary[jx] < minValue)
{
strcpy(minValue, ary[jx]);
minIndex = jx;
}
}
strcpy(ary[minIndex], ary[ix]);
strcpy(ary[ix], minValue);
}

}

//*********************************************
void printArray(char ary[][C_SIZE]){

for(int ix = 0; ix < R_SIZE; ix++){
cout << ary[ix] << endl;
}
cout << endl;
}



------------------------------------------
このプログラムでは、Allen, Jim
          Collins, Bill
          Griffin, Jim
          Smithm, Bart
          Stamey, Marty
という順番に並んでほしいのですが、
実際は C→Sm→A→G→St という
違う順に並んでしまうようです。
どこが間違っているのか思いつかないので
教えてください。

A 回答 (2件)

#1さんの指摘に追加して、


void selectionSort()中の
char minValue[R_SIZE];

char minValue[C_SIZE];
でないとバッファオバーフローとなってしまいます。
理由は...考えてみてください。すぐに分かると思います。(ヒント: strcpy(minValue, ary[ix]);)
    • good
    • 0

あまりしっかり読んでないのですが、



 if(ary[jx] < minValue)

のところは

 if(strcmp(ary[jx], minValue) < 0)

の間違いではないでしょうか?
上の方だと(char*)型のポインタ値の比較になってしまいますよ。
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!