c - 对字符串进行排序并设置它

标签 c pointers

注意:这是作业

我需要对字符串进行排序,并且不允许更改此分配的方法 header 。

我已按如下方式填写方法(使用适当的比较器):

void sortString(const char* input, char* output) {
    strcpy(output,input);
    qsort(output, strlen(output)+sizeof(char), sizeof(char),comparator);
    *output++ = '\0';
    printf("%s\n",output); //prints correct output
}

如果我在最后打印输出,我就会看到我所期望的。

该方法在 for 循环的 main 函数中这样调用:

char* key = malloc(strlen(words[i]) + sizeof(char));
sortString(words[i], key);
printf("key = %s\n", key); //key is blank

我不明白如何让 key 有输出的值。据我了解,我需要通过引用传递,这需要 sortString 获取 char** output 所以我可以传入 &key 但不幸的是我无法更改方法 header ..还有我不知道的另一种方法吗?

最佳答案

您的排序会导致未定义的行为。 (除非您传递的字符串有两个尾随空字符,这不太可能。此外,如果您的比较器首先对较大的字符进行排序,那么您也不会有问题。)

这里发生了什么:

问题是我们有一 block 内存,里面有这些字节:

{'h', 'e', 'l', 'l', 'o', '\0')

您对 qsort 的调用将导致:

{'\0', 'e', 'h', 'l', 'l', 'o'}

然后您递增输出指针,然后打印 {'e', 'h', 'l', 'l', 'o'} ,它不是空终止。这是未定义的行为。

此外,在这次通话之后 key指向 {'\0', 'e', 'h', 'l', 'l', 'o'} .由于output,输出指针的增量没有进行。是局部变量。

所以当你尝试打印 key ,该字符串的第一个字符是空字符,这意味着它打印空字符串。

让我们解决这个问题:

void sortString(const char* input, char* output) {
    strcpy(output, input);
    qsort(output, strlen(output), sizeof(char), comparator);
}

然后调用这个,我们会做:

int main() {
    const char * words[] = {
        "hello",
    };

    char *key = malloc(strlen(words[0]) + 1);
    sortString(words[0], key);

    printf("%s -> %s\n", words[0], key);
}   

我们什么时候需要通过 qsort(words[0], &key)

如果你想要 char **,你只需要通过指针传递指针(所以 sortString() )为 dest 分配内存.

关于c - 对字符串进行排序并设置它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24689869/

相关文章:

c - 将数据保存到 malloc 的 2dim 数组在 C 中不起作用

c - LPC1788 : Communicating with UFDC-1 using SPI

c - 需要澄清指针递增

C: 在 Raspberry Pi 上写入数组指针时出现段错误

c - 将二维指针数组传递给具有一维指针数组参数的函数

c - 对于 readdir_r,entry 和 result 可以有相同的值吗?

c - 我如何为 MIPS 架构编译 nfsutils?

c - 在 while 循环中合并 fgetc 和 putchar

c - 结构体函数指针错误

c - for循环计数器中的数组下标运算符