I have a simple questions. I am new in pointers in C and I don't understand why this is working and I can change value of the pointer
int main()
{
int x = 7;
int *aptr = &x;
printf("%d",*aptr);
*aptr = 21;
printf("%d",*aptr);
}
But this won't print any number
int main()
{
int x = 7;
int *aptr = 21;
printf("%d",*aptr);
}
Thanks for help!
int *aptr = 21;does not store21in*aptr. When=is used in a declaration, it sets the initial value for the thing being declared (which isaptr), not for the “expression picture” used for the declaration (*aptr).In C declarations, we use pictures of a sort to describe the type. Generally, in a declaration like
int declarator,declaratorgives a picture of some expression we will use as anint. For example,int *foosays*foowill be anint, so it declaresfooto be a pointer to anint. Another example is thatint foo[3]saysfoo[i]will be anint, so it declaresfooto be an array ofint. Note that these are declaringfoo, not*fooorfoo[i], so, when an initial value is given, it is for initializingfoo, not*fooorfoo[i].21is not a proper value for a pointer, so the compiler complains. (Integers can be converted to pointers by using casts, but this is a special use case that requires ensuring the integers represent addresses made available in the C implementation.)