The following works:
char *s="hello";
*s="world";
This works by chance. The variable s is pointer, i.e. it holds an address.
That address is set to the position of the string literal "hello" in memory.
One of the confusing things about C is that * is used both to declare a
pointer (as in your first line) and to dereference a pointer, or take the
thing it points to.
In your second line you are dereferencing the pointer. The memory location
occupied by the "h" of your string literal is now set to the address of the
string literal "world".
It is probable that on your machine a char occupies 1 byte whilst a char *
occupies 4 bytes. C will cope with this situation by silently discarding the
top three bytes of the address. The 'h' of "hello" is thus set to the lowest
byte of the address of "world". This could be anything.
but the following gives a segementation fault:
int *p = 0;
*p = 17;
Could anyone please clarify about this?
p is a pointer which is set to 0, or NULL, probably physical location 0 in
memory.
*p = 17 writes a 17 to physical location zero in memory. On most machines,
this will trigger some sort of error because location zero is special, and
normal application are not allowed to write to it.
NULL pointers (or p == 0) are used extensively in C to say "this pointer
doesn't point to anything".