Can I have a pointer that cannot be reassigned directly, but still can be reassigned…
- User
Can I have a pointer that cannot be reassigned directly, but still can be reassigned through other means in C without involving Undefined Behaviour
- Assistant
In C, you can use a const pointer to achieve a pointer that cannot be directly reassigned, while still allowing reassignment through other means. A const pointer is a pointer whose value cannot be changed after initialization.
Here's an example:
#include <stdio.h> int main() { int num1 = 5; int num2 = 10; int* const ptr = &num1; // const pointer to an int printf("Current value: %d\n", *ptr); // dereferencing the const pointer // *ptr = 10; // Error: Cannot change the value through a const pointer directly ptr = &num2; // Error: Cannot reassign the const pointer directly int* nonConstPtr = ptr; // storing the const pointer's value in a non-const pointer *nonConstPtr = 20; // Changes the value through the non-const pointer printf("New value: %d\n", *ptr); // Updated value using non-const pointer return 0; }In this example, we declare a const pointer
ptrto an int and initialize it with the address ofnum1. The const pointer cannot be reassigned directly ( would cause a compilation error). However, we can still modify the value it points to by using a non-const pointer () initialized with the value of . Thus, reassignment of the pointer can still be accomplished indirectly without invoking undefined behavior. - User
But how do I reassign this pointer, e.g. set it Null
- Assistant
If you want to reassign a const pointer to
NULL, you can use a type casting trick with a non-const pointer. Since const pointers cannot be directly assigned toNULL, you can temporarily cast it to a non-const pointer, assignNULL, and then revert it back to a const pointer.Here's an example:
#include <stdio.h> int main() { int num = 5; int* const ptr = # // const pointer to an int printf("Current value: %d\n", *ptr); // dereferencing the const pointer // Reassigning the const pointer to NULL *((int**)&ptr) = NULL; // Type casting trick to change the value if (ptr == NULL) { printf("Pointer is NULL\n"); } else { printf("Pointer is not NULL\n"); } return 0; }In this example, we use a type casting trick
*((int**)&ptr) = NULLto assignNULLto the const pointerptr. The expression*((int**)&ptr)treatsptras a non-const pointer temporarily, allowing us to assignNULL. However, please note that reassigning a const pointer should be used with caution, as it may lead to code that is difficult to understand and maintain.