C99:什么是;int const*ptr";什么意思?

C99:什么是;int const*ptr";什么意思?,c,pointers,constants,c99,C,Pointers,Constants,C99,我在看C99规范(N1256.pdf),它在(第11506页)上写着: “ptr_to_常量指向的任何对象的内容不得通过该指针进行修改,但ptr_to_常量本身可以更改为指向另一个对象。同样,可以修改常量_ptr指向的int的内容,但常量_ptr本身应始终指向同一位置。”(6.7.5.1指针声明符) 从我之前读到的内容来看,以下两种说法导致了相同的行为 int *const constant_ptr; /* This form is mentioned in the standard */ in

我在看C99规范(N1256.pdf),它在(第11506页)上写着:

“ptr_to_常量指向的任何对象的内容不得通过该指针进行修改,但ptr_to_常量本身可以更改为指向另一个对象。同样,可以修改常量_ptr指向的int的内容,但常量_ptr本身应始终指向同一位置。”(6.7.5.1指针声明符)

从我之前读到的内容来看,以下两种说法导致了相同的行为

int *const constant_ptr; /* This form is mentioned in the standard */
int const *constant_ptr; /* This form is NOT mentioned in the standard */
我想知道第二种形式是正确的还是只是一种扩展

提前感谢,, -在这两种情况下,“const”关键字会修改不同的内容

“const int*”表示“int”部分不能更改

“int*const”表示只能更改变量值本身(指针)

这在你引用的文本中有陈述,但以一种更复杂的方式


试着做一些作业,看看有什么错误,你就会明白了。

实际上
int const*constant\u ptr
const int*ptr_to_常量相同
const
关键字会影响左侧的元素,如果没有,则会影响右侧的元素

int const*常量\u ptr
,此处
const
左侧的元素为
int

const int*ptr_至_常数
,这里的
const
在左边没有元素,所以它适用于右边的元素,即
int


这里,只有指针指向的值是常量

int *const constant_ptr;
int const *constant_ptr;
int const * const constant_ptr_to_constant;
int a = 1;
int b = 2;
const int * const p3 = &b;
*p3 = 42; // <------ NOT ALLOWED
p3 = &a; // <------ NOT ALLOWED
这里,指针是常量

int *const constant_ptr;
int const *constant_ptr;
int const * const constant_ptr_to_constant;
int a = 1;
int b = 2;
const int * const p3 = &b;
*p3 = 42; // <------ NOT ALLOWED
p3 = &a; // <------ NOT ALLOWED
这里,只有指针指向的值是常量

int *const constant_ptr;
int const *constant_ptr;
int const * const constant_ptr_to_constant;
int a = 1;
int b = 2;
const int * const p3 = &b;
*p3 = 42; // <------ NOT ALLOWED
p3 = &a; // <------ NOT ALLOWED
这里,指针和指针所指向的值是常量

编辑:


int const*常量\u ptr
,您将指针称为
constant\u ptr
,但如果我保留您的名称方案,则如果'const'关键字位于星号的左侧,并且是唯一这样的关键字,则应将其称为
ptr\u to\u constant

在声明中,那么指针指向的对象是常量,但是 指针本身是可变的

int a = 1;
int b = 2;
const int *p1;
p1 = &a;
p1 = &b; // Can be pointed to another variable
*p1 = 23; // <----- NOT ALLOWED
inta=1;
int b=2;
常数int*p1;
p1=&a;
p1=&b;//可以指向另一个变量

*p1=23;//似乎有些混乱。我在问标准中给出的第二种形式与未给出标准的第二种形式的区别。我将在问题中明确提到这一点。@user926918您提到的所有内容都在标准中——您误解了它。您是对的——我的错。我不确定“int const*constant_ptr;”是否完全是标准的(或者它遵守或不遵守标准的哪个版本),但我已经看到它在许多地方使用过,并且肯定在实践中使用过,应该在任何现代C/C++编译器上编译。谢谢nouney。你能推荐一个关于这种行为的参考吗?@user926918 may问过你。确实有人对解析的可能原因进行了有趣的讨论,但这并没有解决我的问题。我再次检查了C99标准中的限定符规则,但是,据我所知,在这个问题上我保持沉默。也就是说,它并没有说最后一句话是错误的、未指明的或未定义的。因此,我怀疑这种做法似乎是标准的延伸。符号
int-const*ptr
int-const*ptr
都是完全标准化的行为(但彼此不同)。您在问题中引用的是2011年标准(ISO/IEC 9899:2011)第6.7.6.1节指针声明器中的一个示例(因此,从技术上讲,这是非规范性的,但对本问题并不重要)。第6.7.6节声明符中的语法清楚地显示了“
*
类型限定符列表opt
D
”,其中
D
是一个声明符,“类型限定符列表opt”允许使用
const
和其他限定符。谢谢Jonathan Leffler。我看了这一节(C99为6.7.5),它看起来很强大,需要更多的时间。谢谢你的推荐。