You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言使用qsort时void转字符串出现乱码问题求助

问题分析与修复

核心错误:qsort比较函数的类型转换逻辑错误

你遇到的乱码问题根源在compareStrings函数的类型转换:

char *word1 = (char *) &x_void;
char *word2 = (char *) &y_void;

qsort传入的x_void和y_void是数组元素的指针,你的allWords是char**类型(存储字符串指针的数组),所以每个元素是char*,因此x_void实际是char**类型的指针。你错误地取了&x_void(指针自身的地址),这指向的是栈上的临时变量内存,根本不是字符串的起始地址,自然会输出乱码。

正确的转换方式

把void*直接转换成char**,再解引用得到字符串指针:

int compareStrings(const void *x_void, const void *y_void){
    const char *word1 = *(const char **)x_void;
    const char *word2 = *(const char **)y_void;
    printf("%s \n", word1);
    printf("%s \n", word2);
    // 按字典序返回排序比较结果
    return strcmp(word1, word2);
}

其他需要修复的问题

  • 输入处理错误:scanf("%d *[^\n]", &size);格式无效,应改为scanf("%d", &size);,同时要清空输入缓冲区的换行符,否则后续fgets会读取空行:
    scanf("%d", &size);
    getchar(); // 吃掉换行符
    char *sentence = malloc(size + 1);
    fgets(sentence, size + 1, stdin);
    
  • 未实现的核心函数:findSpaces和populateAllWords没有具体逻辑,需要补充:
    • findSpaces需遍历字符串统计空格数量,给spaceAmount赋值;
    • populateAllWords需分割字符串,把每个单词的指针存入allWords数组,可使用strtok实现。

修复后的核心代码片段

int compareStrings(const void *x_void, const void *y_void){
    const char *word1 = *(const char **)x_void;
    const char *word2 = *(const char **)y_void;
    printf("%s \n", word1);
    printf("%s \n", word2);
    return strcmp(word1, word2);
}

int main(){
    int size;
    scanf("%d", &size);
    getchar(); // 处理输入缓冲区的换行符
    char *sentence = malloc(size + 1);
    fgets(sentence, size + 1, stdin);
    
    int spaceAmount = 0;
    // 实现统计空格的逻辑
    for(int i=0; sentence[i]!='\0'; i++){
        if(isspace(sentence[i])){
            spaceAmount++;
        }
    }
    
    char **allWords = malloc((spaceAmount + 1) * sizeof(char*));
    // 实现分割字符串填充数组的逻辑
    char *token = strtok(sentence, " \n");
    int idx = 0;
    while(token != NULL){
        allWords[idx++] = token;
        token = strtok(NULL, " \n");
    }
    
    qsort(allWords, spaceAmount + 1, sizeof(char*), compareStrings);
    
    for (int i = 0; i < spaceAmount + 1; i++){
        printf("%s \n", allWords[i]);
    }
    
    free(sentence);
    free(allWords);
    
    return 0;
}

内容的提问来源于stack exchange,提问作者Bot Ellis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 06:10:38