将Char * ptr转换为Char * ptrArray []以在qsort中使用

时间:2012-01-27 04:09:44

标签: c

使用qsort。

#include <string.h>
#include <stdlib.h>
#pragma once

int cstring_cmp(const void *a, const void *b);


int main()
{   
   int count = 0;
   char * randomStr = "sdjsn9i3ms;sa;'smsn92;w;''[w0p4;dsmsdf";
   char * charArray[] =
    {"s","d","j","s","n","9","i","3","m","s",";","s","a",";","'","s","m","s","n"
    ,"9","2",";","w",";","'","'","[","w","0","p","4",";","d","s","m","s","d","f"};

   size_t strings_len = sizeof(charArray) / sizeof(char *);
   /*void qsort(void *base, size_t nel, 
    size_t width, int (*compar)(const void *, const void *));*/

    qsort(charArray, strings_len, sizeof(char *), cstring_cmp);

    qsort(randomStr, strings_len, sizeof(char *), cstring_cmp);

    // Pause at command prompt
    system("pause");

    return 0;

} // Close function Main

int cstring_cmp(const void *a, const void *b) 
{ 
    const char **ia = (const char **)a;
    const char **ib = (const char **)b;
    return strcmp(*ia, *ib);
}

显然我的第二个qsort无效。是否基于我的cstring_cmp函数进入我的qsort不能支持基础我给它或因为我的基础没有格式化正确输入到qsort对我来说是一个谜。

我的问题是如何动态地,在运行时,动态地或者你可以提出的任何很酷的短语,将char * randomStr动态转换为char * charArray []。我搜索了很多,也许我只是没有问正确的问题,所以我来找你们一些真正的问题回答。

刚刚开始C所以如果你请尽量不用你的答案来煎我的大脑,我的大脑会很感激。

我的最终目标是将randomStr转换为charArray的格式,然后将其转换回randomStr格式,以便我可以查找和替换已经设置的内容。

任何帮助都会很棒,谢谢。

1 个答案:

答案 0 :(得分:1)

首先,如果你使用char *randomStr = "Stuff" you can't change it,那就是未定义的行为。其次,试试这个:

int
cmp_fry_brain(const void *a, const void *b)
{
    return *((const char *)a) - *((const char *)b);
}

/* This is equivalent to the one above (the compiler will likely emit the
 * exact same code).
 */
int
cmp(const void *a, const void *b)
{
    const char *x = a;
    const char *y = b;

    return *x - *y;
}

int
main()
{
    char str[] = "This is the end";
    qsort(str, strlen(str), 1, cmp_fry_brain);
    /* ... */
}