在C中按字母顺序排列随机名称

Sort in alphabetically order random names in C

我尝试按字母顺序对一些名称进行排序,但是当我尝试使用冒泡排序方法将一个字符串复制到另一个字符串时出现 "Segmentation Fault (core dumped)" 错误。 这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
#include <string.h>

int main() {
    char *string[] = {"Nickole", "Bolden", "Eldon", "Darcie", "Lisette", "Furr", "Parthenia", "Tunison", "Andrew", "Michael"};
    char *hold;
    int compare_a, compare_b;
    for(int j = 0; j < 9; j++) {
        for(int i = 0; i < 9; i++) {
            compare_a = string[i][0];
            compare_b = string[i+1][0];
            if( compare_a > compare_b) {           
                strcpy(hold, string[i+1]);
                strcpy(string[i+1], string[i]);
                strcpy(string[i], hold);
            }
        }
    }
    for(int i = 0; i < 9; i++) {
        printf("%s ", string[i]);
    }
    return 0;
}

从未分配 hold 的内存。 strcpy(hold, ..) 这将是一个问题。最好使用 char hold[MAX_NAME_LENGTH]; 或分配 new 相应的内存资源。

此外,数组 string 是编译时常量数组,您无法覆盖它。

您程序中的字符串是字符串文字。文字就像常量,尝试修改它们会导致未定义的行为,尽管它们未指定为 const。它们可能被放置在程序只能读取而不能写入的内存部分。

您试图修改与您的 strcpy() 一起存储字符串文字的内存。您遇到了分段错误,因为您调用了未定义的行为。

现在,如果您将字符串声明为

,您的程序就可以运行了
char string[][10] = {"Nickole", "Bolden", "Eldon", "Darcie", "Lisette", "Furr", "Parthenia", "Tunison", "Andrew", "Michael"};

我将大小设置为 10,因为这里最长的字符串长度为 9。[=15=] 字符额外增加一个字节,表示字符串结束。

这是因为它们不是字符串文字,可以修改。

参见 this post。

正如 Code-Apprentice 在评论中建议的那样,您可以交换指针的值,而不是尝试交换字符串文字。

if( compare_a > compare_b) {
    hold=string[i];
    string[i]=string[i+1];
    string[i+1]=hold;
}

此外,您可以使用 strcmp() 来比较字符串,而不是像

那样只比较字符串的第一个字符
if( strcmp(string[i], string[i+1])>0 ) {
    hold=string[i];
    string[i]=string[i+1];
    string[i+1]=hold;
}

strcmp() returns 如果第二个字符串在字典顺序中第一个之前,则为正值。