Indeed -- this code has plenty of potential for disaster.
GCC will have a good moan about it:
Code:
test.c: In function ‘main’:
test.c:4:25: warning: initialization makes pointer from integer without a cast [enabled by default]
test.c:5:18: warning: initialization makes pointer from integer without a cast [enabled by default]
test.c:7:6: warning: format ‘%c’ expects argument of type ‘int’, but argument 2 has type ‘const char *’ [-Wformat]
test.c:8:6: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat]
It might be a bit clearer to you if I add some explicit casts (I think this is one time where I do prefer C++ -- it won't let you do these assignments without explicit casts.):
Code:
const char *var1 = (const char*)'A';
int *vint = (int*)10;
int value_of_vint = *vint; // !!!!
The extra line there will try to go and read from address 10.
Pointers don't automatically point to anything. If you hadn't initialised them they'd have garbage like any other local variable. To use them for anything you have to write an address to them, e.g.
Code:
int * a = malloc(sizeof(int)); // a = addr on heap
int i;
int *b = &i; // b = addr of i, on stack
int *c = &glob; // address of some global
unsigned int *d = (unsigned int*)0x80001000; // someplace....
You wouldn't hard code an address like that unless you knew what was there and knew the program would be able to access it (e.g. a memory mapped peripheral in an embedded system).