R
rjones872
Consider the following structure:
typedef struct _Struct1
{
int n1;
int n2;
} Struct1, *PStruct1;
Now consider a function that takes a const pointer to this structure.
This allows only read only access to the structure within this Test1()
function.
void Test1(const PStruct1 pData)
{
}
Now let's say I have a global structure in memory that I've also
declared as const so that it cannot be modified as follows:
const Struct1 st = { 0, 0 };
I then issue this single line of code to pass the pointer to the "st"
structure to the Test1() API:
Test1(&st);
The compiler complains with:
error C2664: 'Test1' : cannot convert parameter 1 from 'const Struct1
*' to 'const PStruct1'
Conversion loses qualifiers
Since const Struct1* is equivalent to const PStruct1, I'm not sure
what qualifier is lost. If I remove the const from the "const Struct1
st = { 0, 0 }" it compiles properly but I want to leave that structure
declared as const. Likewise, if I declare the function as "void
Test1(const Struct1* pData)" it compiles as well.
My problem is that I like to use PStruct1 as the variable type instead
of Struct1* everywhere. Here is the code again which may be easier to
read:
typedef struct _Struct1
{
int n1;
int n2;
} Struct1, *PStruct1;
void Test1(const PStruct1 pData)
{
}
void Test2(void)
{
const Struct1 st = { 0, 0 };
Test1(&st); // Compiler complains here
}
What is the recommended way to handle this? Thank you!
typedef struct _Struct1
{
int n1;
int n2;
} Struct1, *PStruct1;
Now consider a function that takes a const pointer to this structure.
This allows only read only access to the structure within this Test1()
function.
void Test1(const PStruct1 pData)
{
}
Now let's say I have a global structure in memory that I've also
declared as const so that it cannot be modified as follows:
const Struct1 st = { 0, 0 };
I then issue this single line of code to pass the pointer to the "st"
structure to the Test1() API:
Test1(&st);
The compiler complains with:
error C2664: 'Test1' : cannot convert parameter 1 from 'const Struct1
*' to 'const PStruct1'
Conversion loses qualifiers
Since const Struct1* is equivalent to const PStruct1, I'm not sure
what qualifier is lost. If I remove the const from the "const Struct1
st = { 0, 0 }" it compiles properly but I want to leave that structure
declared as const. Likewise, if I declare the function as "void
Test1(const Struct1* pData)" it compiles as well.
My problem is that I like to use PStruct1 as the variable type instead
of Struct1* everywhere. Here is the code again which may be easier to
read:
typedef struct _Struct1
{
int n1;
int n2;
} Struct1, *PStruct1;
void Test1(const PStruct1 pData)
{
}
void Test2(void)
{
const Struct1 st = { 0, 0 };
Test1(&st); // Compiler complains here
}
What is the recommended way to handle this? Thank you!