typedef int* ptr_t;
int target;
const ptr_t a = ⌖
*a = 6; //OK
a = ⌖ //<- error: assignment of read-only variable ‘a’
很明显,指针是常量,而不是指向的值。如果使用了#define,则相反。
将修饰符应用于在 typedef 中声明的指针的规则是什么?
举个实际例子,考虑代码
void (**foo)(void);
如何对类型进行类型定义,将顶级指针限定为 const(例如,指向硬件位置),将下一个指针限定为 volatile(例如,可由独立硬件修改)指针功能?
typedef void (**foo)(void)
如果这是我们必须使用的固定声明,如何在源代码中执行上述操作?
最佳答案
C 标准的第 6.7.5.1 节描述了差异。它给出了一个例子:
const int *ptr_to_constant;
int *const constant_ptr;
并说:
The contents of any object pointed to by
ptr_to_constant
shall not be modified through that pointer, butptr_to_constant
itself may be changed to point to another object. Similarly, the contents of theint
pointed to byconstant_ptr
may be modified, butconstant_ptr
itself shall always point to the same location.
最后,该部分的第 4 点描述了 typedef 的使用。
The declaration of the constant pointer
constant_ptr
may be clarified by including a definition for the type ‘‘pointer to int’’.
typedef int *int_ptr;
const int_ptr constant_ptr;
declares
constant_ptr
as an object that has type ‘‘const-qualified pointer to int’’.
关于c - typedef 指针是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16262965/