注意:这是作业
我需要对字符串进行排序,并且不允许更改此分配的方法 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/