void* 类型的打印值 [英] Printing values of type void*

查看:123
本文介绍了void* 类型的打印值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面:

int cmp (void* x, void*y) {
    printf("x: %s | y: %s\n", (char*) x, (char*) y);
    return 0;
}

int main(int argc, char *argv[]) {
    char * strings[] = {"xml", "json"};
    qsort(strings, sizeof(strings), sizeof(strings[0]), cmp);
}

如何看到 x,y 的值是什么?当前的方法会产生乱码,例如:

How would one see what the values of x,y are? The current approach produces gibberish such as:

x: 2?|??|y: 2?|??

x: 2?|?? | y: 2?|??

推荐答案

再次阅读 qsort 的文档.传递给比较函数的参数不是要比较的对象,它们是指向这些对象的指针.所以 x,y 不是字符串本身(即指向字符串字符的指针),而是指向这些指针的指针.

Read the documentation of qsort again. The arguments passed to your comparison function are not the objects to be compared, they are pointers to those objects. So x,y are not the strings themselves (i.e. the pointers to the characters of the strings), but pointers to those pointers.

所以你想写

int cmp (void *x, void *y) {
    printf("x: %s | y: %s\n", *(char**) x, *(char**) y);
    return 0;
}

另请参阅 Joshua 对 qsort 的大小参数问题的回答.

Also see Joshua's answer about the problem with the size arguments to qsort.

最后,qsort 比较函数应该采用指向 const void 的指针,而不仅仅是 void.当您不打算修改它们时,保持 const 是一种很好的做法.在这种情况下,您不打算修改 x 指向的指针,也不打算修改 *x 指向的字符.所以最好写

Finally, the qsort comparison function is supposed to take pointers to const void, not just void. And it is good practice to keep things const when you do not intend to modify them. In this case, you do not intend to modify the pointer that x points to, nor the characters that *x points to. So it would be even better to write

int cmp (const void *x, const void *y) {
    printf("x: %s | y: %s\n", *(const char* const *) x, *(const char* const *) y);
    return 0;
}

这篇关于void* 类型的打印值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆