I have a question:
const int a = 10;
int *ptr;
ptr = (int *)&a;
What is the use of (int *
) in the third line above?
Just like the above if we have:
char str[] = "abc";
char *pc;
pc = str;
Is the above assignment correct?
And if it is, then why is it not in the first case?
const int a = 10;
a
is stored in read-only area (basically to tell compiler that this value cannot be changed).
a
is of type const int
, and &a
is of type const int *
.
So type casting is need to match it:
int *ptr = (int *)&a;
You can avoid it by declaring as below:
int const *ptr = &a;
p
is of type const int
, types are matching, no issue.
updated for your query:
Pointer to constant can be declared in the following two ways.
const int *ptr;
int const *ptr;
Both are same. In this case we can change pointer to point to any other integer variable, but cannot change value of object (entity) pointed using pointer ptr
.
But this is not the same as 1st: int *const ptr;
— this is a Constant pointer to a variable.
In this case we can change value of object pointed by pointer, but cannot change the pointer to point another variable.