I edited the code you had made making changes to the parts I commented on and received no seg fault, the wrong points I found:
The first parameter of the function was actually incorrect, you ask for a string when you actually need an array, this can cause in some cases you get SEGFAULT errors and of course will not sort correctly in cases where there is no error. The cases that generate errors are the cases where your string has smaller size than the vector(array of strings) that you intend to work, in these cases you end up accessing invalid positions of the string, actually I don’t 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 a function argument strcpy
The other error is the matrix aux
, the use of it is incorrect and also makes the correct ordering impossible, you only need an auxiliary string, the copy of the data in words
should be done on its own and not in the matrix aux
that is not being used for anything other than assisting in the ordering loop, in fact it may be just a string.
here’s 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] = {'\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;
}
the first parameter of your function:
void quickSortWordsArray(char words[],int esq,int dir)
, you’re asking for a string, but I guess you wanted a string array isn’t it? when you dowords[j]
is accessing a character and not a string, is that what you want? Another point is the while loop, you are copying everything to the matrixaux
, but I think it really should be:strcpy(words[j],words[j-1]);
– Paulo Marcio