簡體   English   中英

Qsort不會對指向字符串的指針數組進行排序

[英]Qsort doesn't sort array of pointers to strings

在這個C程序中,我用鍵盤輸入的字符讀到了char指針。 指針存儲在指針數組中。 然后我想通過功能比較用qsort對數組進行排序。 我給它指向我的指針數組的指針。 它根本不對數組排序。 我不知道我是否在這里UB,或者我因分配錯誤而錯過了內存。

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

bool read_word(char ***a, int *length);
int comparison(const void *p, const void *q);


int main()
{
    int *length = malloc(sizeof(int));
    *length = 0;
    char **array = malloc(sizeof(char *));
    bool go = false;

    while(go == false)
    {
        printf("Enter word: ");

        go = read_word(&array,length);
    }

    qsort(array, *length - 1,sizeof(char *), comparison);

    printf("\n");


    for(int i = 0; i < *length; i++)
        printf("%s\n", array[i]);

    return 0;
}

bool read_word(char ***a, int *length)
{
    char ch;

    ++*length;

    char *word = malloc(20 * sizeof(char) + 1);
    char *keep_word;

    char **temp = realloc(*a,*length * sizeof(*a));

    if(!temp)
        exit(EXIT_FAILURE);

    *a = temp;

    keep_word = word;

    while((ch = getchar()) != '\n')
        *keep_word++ = ch;

    *keep_word = '\0';

    if(word == keep_word)
    {
        free(word);
        --*length;
        return true;
    }



    (*a)[*length - 1] = word;

    printf("%s", (*a)[*length -1]);
    printf("\nh\n");
    return false;
}

int comparison(const void *p, const void *q)
{
    const char *p1 = p;
    const char *q1 = q;


    return strcmp(p1,q1);
}

改成

int length = 0;//no need malloc
char **array = NULL;//first value is NULL

qsort(array, length, sizeof(char *), comparison);//not length-1

int ch;//type of return value of getchar is int

for(int i = 0; i < 20 &&  (ch = getchar()) != '\n'; ++i)//i : guard

const char *p1 = *(const char **)p;//qsort pass pointer to object to comparison function  
const char *q1 = *(const char **)q;//if char *, char **

你做

keep_word = word;

然后

if(word == keep_word)

括號中的條件始終為true。

附帶說明一下,您的程序容易出錯並且難以理解,因為您使用指針的方式過多。 main()length應該是int ,而不是int* ,array應該是char* ,而不是char** read_worda應該是char** ,而不是char*** 除非必要,否則不要使用指針!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM