小编Cur*_*s91的帖子

C中volatile表达式中的指针

说我有一个结构

typedef struct A{

int a1;
int *a2;

}A_t;
Run Code Online (Sandbox Code Playgroud)

现在如果我声明这个结构的实例是volatile的 -

volatile A_t trial;
Run Code Online (Sandbox Code Playgroud)

我使用volatile指针来访问这个volatile结构.

volatile A_t *ptrToTrial = &trial;
Run Code Online (Sandbox Code Playgroud)

如果我尝试这样做:

int *ptrToField = ptrToTrial->a2;
Run Code Online (Sandbox Code Playgroud)

应该ptrToField也是不稳定的吗?编译器prtToField是否会在没有明确提及的情况下知道它是volatile,因为它是通过ptrToTrialvolatile 访问的?

如果有功能 -

function trialFunction(A_t *trialptr)
{
     int *p = trialptr->a2;

}
Run Code Online (Sandbox Code Playgroud)

如果我们用上面声明的volatile ptr调用这个函数 -

trailFunction(ptrToTrial)
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:volatile A_t* is incompatible with parameter of type A_t.

因此,如果我将函数定义更改为include volatile,我看不到错误.

function trialFunction(volatile A_t *trialptr)
{
     int *p = trialptr->a2;

}
Run Code Online (Sandbox Code Playgroud)

编译器是否也应该抱怨指针p- 因为ptrialptr->a2是非易失性的并且是易失性的?

c struct pointers

9
推荐指数
1
解决办法
633
查看次数

标签 统计

c ×1

pointers ×1

struct ×1