How does C interpret int in pointers and why it differ from char pointer? -
#include<stdio.h> void main() { int *c=12345; printf("dec:%d hex:%x", c ,&c); // (1) }
the line (1) prints
dec:12345 hex:8af123
where 8af123
address random , machine dependent.
when put in
printf("dec:%d", *c); // (1)
it fails, obviously.
so question per theoretical concept:
*c
should holds value12345
not. why?
and in code:
#include<stdio.h> void main() { char *c='a'; printf("address store in c:%d value point c:%c address of c:%x", c,*c ,&c); //focus line }
output is:
adderess store in c:9105699 value point c:a address of c:8af564
- why storing 'a' in
*c
instead inc
?
i using gcc compiler 4.4.3.
int *c=12345;
you made pointer points (probably) invalid address 12345
.
if pass c
(no *
) printf
, you're passing pointer itself. therefore, printf
sees number 12345
, , prints that. has no way of knowing that's supposed pointer.
if pass *c
, printf
, you're dereferencing pointer – you're passing value @ memory address 12345
.
since that's not valid address, dereference operation crash (to precise, behave undefinededly) before ever gets printf
.
Comments
Post a Comment