I edited the code that you had made by making changes to the parts I commented and did not receive any segfaults, the wrong points I found:
The first parameter of the function was actually incorrect, you request a string when you actually need an array, this can cause you to get SEGFAULT errors in some cases and of course it will not sort correctly in cases where it does not error. The cases that generate errors are the cases in which your string is smaller than the vector (array of strings) that you intend to work, in these cases you end up accessing invalid positions of the string, to tell you the truth I do not even know how it compiled: strcmp(words[j], words[pivo]);
, since words
is a string words[j]
returns a character and not a string and therefore should not be accepted as an argument of the function strcpy
The other error is the aux
array, its use is incorrect and also makes it impossible to sort correctly, you just need an auxiliary string, the copy of the data in words
must be done in itself and not in the array aux
that is not being used for anything other than assisting in the sort loop, in fact it can be just a string.
Here is the code that worked:
#include <cstring>
#include <iostream>
void quickSortWordsArray(char words[][20],int esq,int dir){
int i,j,pivo=esq;
char aux[20] = {'#include <cstring>
#include <iostream>
void quickSortWordsArray(char words[][20],int esq,int dir){
int i,j,pivo=esq;
char aux[20] = {'%pre%'};//20 é o MAX_COLUMNS
for(i=esq+1;i<=dir;i++){
j=i;
if((strcmp(words[j], words[pivo])<0)){
strcpy(aux, words[j]);
while(j>pivo){
strcpy(words[j],words[j-1]);
j--;
}
strcpy(words[j], aux);
pivo++;
}
}
if(pivo-1 >= esq){
quickSortWordsArray(words,esq,pivo-1);
}
if(pivo+1<=dir){
quickSortWordsArray(words,pivo+1,dir);
}
}
void printStrings(char strs[][20], unsigned int n) {
for (unsigned int i = 0; i < n; i++)
std::cout << strs[i] << std::endl;
}
int main() {
char words[][20] = {"ola", "alo", "helloWworld", "bbbbbbbbb", "aaaaaaaaaaaa", "ababababab"};
quickSortWordsArray(words, 0, 5);
printStrings(words, 6);
system("pause");
return 0;
}
'};//20 é o MAX_COLUMNS
for(i=esq+1;i<=dir;i++){
j=i;
if((strcmp(words[j], words[pivo])<0)){
strcpy(aux, words[j]);
while(j>pivo){
strcpy(words[j],words[j-1]);
j--;
}
strcpy(words[j], aux);
pivo++;
}
}
if(pivo-1 >= esq){
quickSortWordsArray(words,esq,pivo-1);
}
if(pivo+1<=dir){
quickSortWordsArray(words,pivo+1,dir);
}
}
void printStrings(char strs[][20], unsigned int n) {
for (unsigned int i = 0; i < n; i++)
std::cout << strs[i] << std::endl;
}
int main() {
char words[][20] = {"ola", "alo", "helloWworld", "bbbbbbbbb", "aaaaaaaaaaaa", "ababababab"};
quickSortWordsArray(words, 0, 5);
printStrings(words, 6);
system("pause");
return 0;
}