为什么将指针传递给具有恒定指针类型参数的函数时不需要类型铸造?

发布于 2025-02-06 12:59:40 字数 493 浏览 1 评论 0原文

我初始化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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

回眸一笑 2025-02-13 12:59:40

为什么我不需要键入char类型指针到const char type指针?

由于隐式资格转换。特别是,可以将指向非Conconst类型的指针转​​换为相应的const类型的指针。

nofollow noreferrer“> nectit转换

类型指针的prvalue可以将CV符号类型t转换为Prvalue指针,转换为更CV的相同类型t(换句话说,constness,可以添加波动率)。

“更多” CV合并意味着

  • a 指向不合格类型的指针可以转换为const ;

    的指针

    ...

(强调我的),

例如,

int i = 0;
const int *p = &i; // conversion to const happens here

Why I don't need to type cast the char type pointer to const char type pointer?

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:

A prvalue of type pointer to cv-qualified type T can be converted to a prvalue pointer to a more cv-qualified same type T (in other words, constness and volatility can be added).

"More" cv-qualified means that

  • a pointer to unqualified type can be converted to a pointer to const;

    ...

(emphasis mine)

For example,

int i = 0;
const int *p = &i; // conversion to const happens here
段念尘 2025-02-13 12:59:40

从指针到非const的转换可以自由转换为指针转换为const类型。这样做不会更改指向类型,而只是将限制添加到如何使用指向类型的方式中。

例如:

char str[] = "test";
str[0] = 'p';   // OK
const char *p = str;
p[0] = 't';     // ERROR: pointed-to type is const

这适用于 all 类型的限定符,其中包括限制volatile

拼写出来:

对于任何限定词 q ,指向非 q qualified类型的指针可能是
转换为指针转换为该类型的 q 合格版本;这
原始指针中存储的值应比较
相等。

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:

char str[] = "test";
str[0] = 'p';   // OK
const char *p = str;
p[0] = 't';     // ERROR: pointed-to type is const

This applies to all type qualifiers, which includes restrict and volatile.

Section 6.3.2.3p2 of the C standard spells this out:

For any qualifier q, a pointer to a non-q-qualified type may be
converted to a pointer to the q-qualified version of the type; the
values stored in the original and converted pointers shall compare
equal.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文