I'm trying to sort an array of strings that is implemented using a pointer to a pointer. The code I am using is:
void sort(){
char** names;
for(int i = 1; i < size; i++){
int k = i;
while((strcmp(names[k],names[k-1]) < 0) && (k > 0)){
char* temp;
temp = names[k];
names[k] = names[k-1];
names[k-1] = temp;
k--;
}
}
}
names is already initialized and filled with 7 names in another method. I get a seg fault at this line
names[k] = names[k-1];
names[k-1] = temp;
but I'm not sure why exactly. I get the seg fault after the first iteration of the while loop, and k is decremented to 0. It never returns to the for loop to increment i and k again. Can someone explain why I am getting the seg fault and how to fix it?
(strcmp(names[k],names[k-1]) < 0) && (k > 0)
is wrong. The correct form is
(k > 0) && (strcmp(names[k],names[k-1]) < 0)
The sequence matters because names[k-1]
is unsafe to read when k
is zero. &&
always computes its left operand first and only computes its right operand when the left is true