I have struct and function declared as follows
typedef struct myStruct
{
//Some attributes
}myStruct_t, *pMyStruct_t;
void func(myStruct_t* someStruct);
When I declare a struct pointer as follows and pass it to the function, all is fine
volatile pMyStruct_t pStruct;
But when I declare the pointer this way I get an error that the volatile qualifier is discarded in the function
volatile myStruct_t* pStruct;
I guess my question is how come the first method works and no qualifier errors are raised? What is the difference between the two ways the pStruct
variable is declared?
CodePudding user response:
These declarations
volatile pMyStruct_t pStruct;
and
volatile myStruct_t* pStruct;
are different.
The first one means the following
myStruct_t* volatile pStruct;
That is in the first declaration it is the pointer itself that is volatile while in the second declaration the pointer itself is not volatile.
You may initialize the function parameter with a value of a pointer that is itself is volatile. But you may not discard the qualifier for the pointed object
CodePudding user response:
The first one
volatile pMyStruct_t pStruct;
Creates a volatile
variable pstruct
that is passed by copy to your function.
The memory where it points to is not volatile
.
The second one
volatile myStruct_t* pStruct;
defines a pointer to a volatile
memory.
These are very different.
This also shows why it is widely regarded to be a terrible idea to hide a pointer type into a typedef
.
CodePudding user response:
volatile pMyStruct_t pStruct;
This code equivalent to this:
myStruct_t* volatile pStruct;
There is a difference with this:
volatile myStruct_t* pStruct;
Difference in that, which variable will be volatile. In first case, pointer to the struct itself will be volatile. In second case, struct object will be volatile, not pointer. It seems to me, that second choice is yours. Any way, there is little sense to make pointer volatile.
You can typedef
pointer with the volatile keyword:
typedef volatile struct myStruct
{
//Some attributes
}myStruct_t, *pMyStruct_t;
But in this case, struct will always be volatile, I don't know is this acceptable for you.