为什么将指针传递给具有恒定指针类型参数的函数时不需要类型铸造?
我初始化char []
带有“ hello”
字符串的数组:
char str[] = "hello";
func(str);
现在,char []
数组传递给函数,采用一个const char*
指针参数:
void func(const char* str)
{
puts(str);
}
输出:
hello
我为什么不需要将char []
数组键入const chard*
指针?
I initialize a char[]
array with a "hello"
string:
char str[] = "hello";
func(str);
Now, the char[]
array is passed to a function, taking a const char*
pointer parameter:
void func(const char* str)
{
puts(str);
}
Output:
hello
Why don't I need to typecast the char[]
array to a const char*
pointer?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于隐式资格转换。特别是,可以将指向非Conconst类型的指针转换为相应的
const
类型的指针。从 nofollow noreferrer“> nectit转换:
(强调我的),
例如,
Because of the implicit qualification conversion. In particular, a pointer to a nonconst type can be converted to a pointer to the corresponding
const
type.This can be seen from implicit conversion:
(emphasis mine)
For example,
从指针到非const的转换可以自由转换为指针转换为const类型。这样做不会更改指向类型,而只是将限制添加到如何使用指向类型的方式中。
例如:
这适用于 all 类型的限定符,其中包括
限制
和volatile
。拼写出来:
A conversion from a pointer to a non-const can be freely converted to a pointer to a const type. Doing so doesn't change the pointed-to type, but simply adds restrictions to how the pointed-to type is used.
For example:
This applies to all type qualifiers, which includes
restrict
andvolatile
.Section 6.3.2.3p2 of the C standard spells this out: