c - typedef 指针是如何工作的

标签 c typedef

typedef int* ptr_t;
int target;
const ptr_t a = ⌖
*a = 6;            //OK
a = &target;       //<- 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, but ptr_to_constant itself may be changed to point to another object. Similarly, the contents of the int pointed to by constant_ptr may be modified, but constant_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/

相关文章:

c - 关于 epoll_ctl()

C: 在 linux 中发送 http get 请求

c++ - 常量表达式类型定义

c++ - double[2] 错误 vector

时间:2019-03-08 标签:c++typedefgenerics

c++ - 想要的CWMP CPE(客户端)和ACS(服务器)

c - pjsip pj_timer_heap_schedule 崩溃

c - 在 C 中打印出文件名及其大小

c++ - 在c++中,当我经常使用多级指针时,使用typedef来简化它是不是一个好方法?

c++ - 编译器差异 : Interaction between alias resolution and name lookup