#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int soSanh(char const *str1, char const *str2);
void sapXep(char *ten[], int soLuongTen);
void swap(char *str1, char *str2);
int main(){
char *str[] = {"viet", "Anh", "viet"};
// Sap xep theo alphabet
sapXep(str, 3);
// Hien thi ket qua 3 string sau khi sap xep theo alphabet
for(int i = 0; i < 3; i++){
printf("%s\n", str[i]);
}
return 0;
}
int soSanh(char const *str1, char const *str2){
int compareResult = strcmp(str1, str2);
if(compareResult < 0){
return -1;
}
else if(compareResult == 0){
return 0;
}
else
{
return 1;
}
}
void sapXep(char *ten[], int soLuongTen){
for(int i = 0; i < soLuongTen - 1; i++){
for(int j = i; j < soLuongTen; j++){
int ketQuaSoSanh = soSanh(ten[i], ten[j]);
if(ketQuaSoSanh > 0){
swap(ten[i], ten[j]);
}
}
}
}
void swap(char *str1, char *str2){
char *temp = (char *)malloc((strlen(str1)+1)*sizeof(char));
if (temp != NULL)
{
strcpy(temp, str1);
strcpy(str1, str2);// Error!!! Segmentation fault
strcpy(str2, temp);
}
free(temp);
}
Em có đề bài về việc sắp xếp mảng string c-type theo chiều tăng dần, nhưng khi chạy thử thì em gặp phải lỗi segmentation fault. Qua việc debug thì em đã phát hiện được có vẻ lỗi nó nằm ở hàm strcpy() ở trong function swap. Nhưng em không hiểu lý do sao nó lại lỗi như vậy.
Bác nào biết chỉ cho em chỗ sai với ạ.
swap con trỏ được rồi.
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?