本文介绍了当给定const char *作为第一个参数时,C标准库函数`strchr`如何返回指向非const的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 使用gcc / g ++编译给定的代码示例成功。对于当您调用 strchr code> char * 你需要一个 char * 回来,这样你就不需要对结果进行强制转换。 C不支持函数重载,因此使用相同的 strchr 函数来搜索 char * 和 const char * 。它在所有情况下都返回一个非const指针。如果你使用 const char * 来调用它,它基本上抛弃了 const ,因此调用者有责任使用它安全地(例如立即将结果分配给 const char * ,以避免任何不安全地使用返回的指针)。Yes, it could have been, but it isn't done like that. The original version of C didn't support const at all, so it was always the programmer's responsibility to avoid trying to modify string literals. If different function names were used then it would have broken existing code that used strchr safely. It would have slowed the adoption of the new const keyword if traditional C code like this suddenly stopped compiling:char arr[] = "foo bar";*strchr(arr, 'r') = 'z';The "spirit of C" is that it doesn't try to stop you doing unsafe things, it's your job to write correct code.In C++ strchr is overloaded to preserve constness:char* strchr(char*, int);const char* strchr(const char*, int);This means it automatically does the right thing, and it's much harder to accidentally write unsafe code with strchr. 这篇关于当给定const char *作为第一个参数时,C标准库函数`strchr`如何返回指向非const的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-23 07:36
查看更多