Though it is very basic and might seem silly, I am trying to understand what is difference between the int *ptr = 45
or 0xc8750;
(some number) vs. int *ptr= &a;
(address of variable).
What I already know is:
- Pointers are made to store address of variables and to modify contents of pointed variables ( but I want to know how it will be achieved)
- In latter case, I can assign
*ptr
to different address that is legal. - But, in first case it is illegal!.
Why the latter is illegal if both address/number are integers? How differently will they be treated while storing in memory?
I have two piece of code/programs basically to highlight the same:
case-1:
#include <stdio.h>
int main()
{
int *ptr = 0xc42; // is this stored in read only memory?!! which later leads to seg faults in further assignments?!
*ptr = 45; //illegal leads seg fault.
return 0;
}
case-2:
int main()
{
int a=10, b=20;
int *ptr = &a; // is here get any special treatment and object will be created for *ptr!!!
*ptr = &b; //legal
printf(" *ptr = %d \n", *ptr);
*ptr = 20; //legal !!
printf(" *ptr = %d \n", *ptr);
*ptr = 50; //legal
printf(" *ptr = %d \n", *ptr);
return 0;
}
As we can see the *ptr = 20
and *ptr = 50
are legal and fine! (No segmentation faults).
Why is this assignment of int *ptr = 0xc989
or 5 different from int *ptr = &variable
?.