I am experimenting with C, I have declared a void pointer to const. In normal pointer to const, we cannot change the value of address its pointing by dereferencing it. But if we use a void pointer to const it can be changed. Similar behavior is seen for constant pointer, a void constant pointer's address can be changed! Is this the expected behavior? or am I missing something? I am using following code:
const void *ptr2; //pointer to const
void const *ptr3; // const pointer
uint32_t modNum32 = 0xDEADBEEF;
ptr2 = &modNum32;
*((uint32_t*)ptr2) = 4; // this works!
printf("After modifying a void pointer to const: %X, This don't work with normal pointer to const\n",modNum32);
ptr3 = &modNum32;
*((uint32_t*)ptr3) = 5; //This works as expected
printf("%X\n",modNum32);
printf("Address of void const pointer before incrementing %p\n",ptr3);
ptr3 ;//this works!
printf("Address of void const pointer after incrementing %p! this don't work in normal const pointers\n",ptr3);
Below is the console O/P:
After modifying a void pointer to const: 4, This don't work with normal pointer to const
5
Address of void const pointer before incrementing 0x7ffe61cf0710
Address of void const pointer after incrementing 0x7ffe61cf0711! this don't work in normal const pointers
CodePudding user response:
This declaration
void const *ptr3; // const pointer
does not declare a constant pointer. To declare a constant pointer you need to write
void * const ptr3 = &modNum32; // const pointer
Pay attention to that you need to initialize it explicitly if is a block scope declaration.
In this expression statement
*((uint32_t*)ptr2) = 4; // this works!
you discarded the qualifier const.
As the pointed object is not a constant object then you can change it.
You should write
*(( const uint32_t*)ptr2) = 4;
to prevent modification. In this case the compiler will issue an error.
Node: a declaration of a constant pointer to a constant object will look like
const void * const ptr1 = &modNum32;